1

我有两个文件(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;
4

2 回答 2

11

问题在于

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

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

 twoStroke.i.i1+twoStroke.i.i2;
于 2017-11-29T07:47:52.320 回答
7

错字:

twoStrokeEngine.internal.i1=20;

必定是

twoStrokeEngine.i.i1=20;

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

于 2017-11-29T07:47:37.717 回答