#定义整个库的范围?
假设我有一个常量:
#define PI 3.14
假设我有一个包含多个头文件和源文件的静态库。如果我在头文件中声明它,它的范围是否适用于所有源文件?或者源文件是否需要包含带有 PI
声明的标头?
Say I have a constant:
#define PI 3.14
Say I have a static library with multiple header and source files. If I declare this in the header file, will its scope apply to all of the source files? Or do the source files need to include the header with the declaration of PI
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
他们需要包含包含 #define PI 3.14 的文件,否则预处理器将无法读取 #define 行,随后编译将失败。
在 C++ 中,考虑编译过程的一个好方法是,每个单独的 C++ 文件首先通过预处理器运行,该预处理器获取所有 #define、#include 和其他预处理器语句,并在整个代码中替换它们,然后编译(在此时,C++ 文件和通过 #include 引入的任何内容几乎被视为一个非常大的单个文件),然后,链接器获取所有 C++ 文件的预处理/编译阶段的最终输出并进行汇编将它们合并到一个最终输出文件中。预处理器(处理定义)在编译阶段之前工作,而不是在链接期间工作。
They will need to include the file which contains #define PI 3.14, otherwise the preprocessor will not read the #define line, and subsequently the compile will fail.
In C++, a good way to think of the compile process is that each individual C++ file is first run through a preprocessor, which takes all the #define, #include, and other preprocessor statements and replaces them throughout the code, then compiled (at this point, the C++ file and anything brought in via #include treated almost as if they were one very large single file), then after that, a linker takes the final output of the preprocess/compile stage for all of the C++ files and assembles them into one final output file. The preprocessor (Which handles the defines) works before the compile stage, not during linkage.
该定义必须包含在每个模块中。
从技术上讲,它没有“范围”。它只是在编译之前发生的文本替换操作。您还可以查看编译器设置以找到指定预处理器定义的方法。这通常是可以通过 IDE 轻松访问的项目设置。
The definition has to be included in each module.
Technically, it has no "scope". It is only a text replacement operation that happens prior to compilation. You could also look into your compiler settings for a way to specify pre-processor definitions. This is often a project setting available easily through your IDE.
它们需要包含定义,但是如果您需要跨所有文件进行定义,则可以进行编译器级别切换。
They will need to include the define, however if you need a define across all files you can do a compiler level switch.