在头文件中为结构成员使用宏 #define 时无法编译 C 代码

Unable to compile c code, when using the macro #define for struct member in header file

我有两个文件(average.h、average.c)。在结构的定义中,我使用了 #ifdef INTERNAL

#ifndef AVERAGE_H_
#define AVERAGE_H_


typedef struct str_internal {
    int i1;
    int i2;
} internal;

typedef struct str_speed {
    int lowest;
    int highest;
#ifdef INTERNAL
    internal i;
#endif
} speed;


extern double average(speed twoStroke);

#endif /* AVERAGE_H_ */

average.c的内容是,

#include <stdio.h>
#include "average.h"

double average(speed twoStroke) {
    double average = (twoStroke.highest + twoStroke.lowest) / 2.0;

#ifdef INTERNAL
    average += twoStroke.internal.i1+twoStroke.internal.i2;
#endif

    return average;
}


int main() {
    speed twoStrokeEngine;
    twoStrokeEngine.highest = 70;
    twoStrokeEngine.lowest = 50;
#ifdef INTERNAL
    twoStrokeEngine.internal.i1=20;
    twoStrokeEngine.internal.i2=10;
#endif
    double avg = average(twoStrokeEngine);
    printf("Average speed of two stroke engine is: %f", avg);
    return 0;
}

当我尝试编译这段代码时, gcc -DINTERNAL -o average.exe average.c 我收到以下错误消息。

average.c:8:22: error: ‘speed {aka struct str_speed}’ has no member named ‘internal’
  average += twoStroke.internal.i1+twoStroke.internal.i2;
                      ^
average.c:8:44: error: ‘speed {aka struct str_speed}’ has no member named ‘internal’
  average += twoStroke.internal.i1+twoStroke.internal.i2;
                                            ^
average.c: In function ‘main’:
average.c:20:17: error: ‘speed {aka struct str_speed}’ has no member named ‘internal’
  twoStrokeEngine.internal.i1=20;
                 ^
average.c:21:17: error: ‘speed {aka struct str_speed}’ has no member named ‘internal’
  twoStrokeEngine.internal.i2=10;

打字错误:

twoStrokeEngine.internal.i1=20;

应该

twoStrokeEngine.i.i1=20;

等等。 i是成员,不是internal。后者是typedefstruct.

问题出在

  twoStroke.internal.i1+twoStroke.internal.i2;
            ^^^                   ^^^^

internal是类型,不是可以访问的成员。您需要访问成员变量。 internal 类型的成员变量是 i,因此您的语句应该类似于

 twoStroke.i.i1+twoStroke.i.i2;