![](/img/trans.png)
[英]How to include multiple directories to search header files in C preprocessor
[英]C preprocessor in include header files
我有一个在名为data.h的头文件中定义的结构。
我将data.h包含在myfile.c中。
在结构中,我将部分变量用:
#ifndef TEST
int x;
#endif
在myfile.c中,我有:
#ifdef TEST
localx++;
#else
mystruct.x++; //<-compiler complains on this line when compiling
#endif
当我尝试使用-DTEST
进行编译时,出现编译器抱怨mystruct
类型不包含名为x
的字段。 这怎么了?
我没有C编译器,所以这里是我刚输入的内容:
在data.h中
typdef struct {
#ifndef TEST
int x;
#endif
int y;
} coords;
在myfile.c中
#include "data.h"
static coords coord1;
int localx;
int main( )
{
#ifdef TEST
localx = 1;
#else
coord1.x = 1;
#endif
coord1.y = 2;
printf("%i\n", coord1.x);
printf("%i\n", coord1.y);
printf("%i\n", localx);
return 0;
}
当我键入cc myfile.c
而不是cc myfile.c -DTEST
时, cc myfile.c -DTEST
编译。我正在使用此处引用的MIPSPro C编译器。
您最近的编辑(在任何人阅读此书时,可能会有所不同)将在具有一堆printf()
语句的部分中出现问题。 该行:
printf("%i\n", coord1.x);
无论TEST
预处理器宏的设置如何,都引用结构的x
成员。 当x
成员不存在时,它也必须在条件编译部分中才能正确编译(而不是根本不编译)。
由于您在字段x中使用ifndef,因此只有在未定义TEST的情况下才可以使用它!
#ifdef允许仅在定义了指定为参数的宏的情况下编译程序的一部分,而不管其值是什么。 例如:
#ifdef TABLE_SIZE
int table[TABLE_SIZE];
#endif
在这种情况下,代码行int table [TABLE_SIZE]; 仅当先前使用#define定义TABLE_SIZE时,才对其进行编译,而与它的值无关。 如果未定义,则该行将不包含在程序编译中。
#ifndef的作用恰恰相反:#ifndef和#endif指令之间的代码仅在指定的标识符先前未定义时才编译。 例如:
#ifndef TABLE_SIZE
#define TABLE_SIZE 100
#endif
int table[TABLE_SIZE];
在这种情况下,如果在到达这段代码时尚未定义TABLE_SIZE宏,则将其定义为值100。如果已经存在,则它将保留其先前的值,因为不会定义#define指令。被执行。
除错字(typdef)外,您的示例对我来说使用gcc可以很好地编译。
编辑:新的示例不应该编译。 您需要在#ifdef指令中包装对“ x”的所有引用。
另外,gcc在文件列表之前接受-D标志,但我无权访问MIPSpro。 文档说您的命令行混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.