简体   繁体   English

多个#ifndef语句-应用哪一个

[英]Multiple #ifndef statements - which one gets applied

Say I have five files: main.c, sample1.c, sample1.h, sample2.c and sample2.h , where in each of these files DEBUG_PRINTS is defined as follows: 说我有五个文件: main.c, sample1.c, sample1.h, sample2.csample2.h ,其中在每个文件中, DEBUG_PRINTS的定义如下:

#ifndef DEBUG_PRINTS
#define DEBUG_PRINTS 0
#endif

and the code is compiled using gcc: 并使用gcc编译代码:

gcc -Wall main.c sample1.c sample2.c -o main

Now I change the value of DEBUG_PRINTS in one file to 1 . 现在,我将一个文件中的DEBUG_PRINTS的值更改为1 Without printing to the terminal how can you determine, which value will be applied? 在不打印到终端的情况下,如何确定将应用哪个值?

Additionally, how can I define DEBUG_PRINTS locally per file - the same as using the static keyword for variables? 此外,如何在每个文件的本地定义DEBUG_PRINTS就像对变量使用static关键字一样?

Each file is compiled separately. 每个文件分别编译。 Macros from one file are not visible in any other file. 一个文件中的宏在其他任何文件中均不可见。 Once the files are independently compiled, the resulting objects are linked together to create an executable. 一旦文件被独立编译,结果对象将链接在一起以创建可执行文件。

#ifndef means if the macro isn't defined at all in that file before or in an header you included. #ifndef表示该宏是否在您包含的标头之前或标头中根本没有定义 In your case, it defaults to 0. 您的情况下,默认值为0。

If you change DEBUG_PRINTS in that one file to 1 , it will override that #define in #ifndef found in the header file. 如果将一个文件中的DEBUG_PRINTS更改为1 ,它将覆盖在头文件中的#ifndef中的#define You are basically locally defining or overriding the default DEBUG_PRINTS in the imported header file to 1 . 您基本上是在本地定义或将导入的头文件中的默认DEBUG_PRINTS覆盖为1

Otherwise, macros are visible only to this file or header. 否则,宏仅对该文件或标头可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM