简体   繁体   English

预处理器命令顺序

[英]Preprocessor command order

I know that when I have only one source file in C++, preprocessor commands are done in order they were written, but what if I have more than one source file?我知道当我在 C++ 中只有一个源文件时,预处理器命令会按照它们被写入的顺序执行,但是如果我有多个源文件怎么办? How is the decision made, which source file should be taken at first?如何做出决定,首先应该采用哪个源文件? I've written in both source files such code:我在两个源文件中都写了这样的代码:

#ifndef b 
#define b 10
int a = 15;
#endif

and when I compile, there is an error, that variable a has been already defined.当我编译时,出现错误,该变量 a 已被定义。 But why, if there is a command #ifndef and #endif?但是,如果有命令#ifndef 和#endif,为什么?

I am assuming you get this error in the linker stage.我假设您在 linker 阶段遇到此错误。 This is because both your source files define a symbol with the same name, and the linker gives up when trying to merge the object code from each file.这是因为您的两个源文件都定义了一个具有相同名称的符号,并且 linker 在尝试合并每个文件中的 object 代码时放弃了。 If your intent is to let at least one of the files have its own separate version of a , declare it in that file as static .如果您的意图是让至少一个文件有自己的单独版本a ,请在该文件中将其声明为static Then the linker error should go away as the static a is limited to its own file.那么 linker 错误应该是 go 因为 static a限制在它自己的文件中。

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

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