c ++中预编译器定义的范围是什么?

What is the scope of pre-compiler define in c++?

预编译器的作用域是在它定义的地方定义文件吗? 例如:

三个文件:

test1.hpp/test1.cpp
test2.hpp/test2.cpp
test3.hpp/test3.cpp

test1.cpp内的一个:

#ifndef test1_hpp
#define test1_hpp

// some declarations

#endif 

test2.hpptest.hpp#include test1.hpp。如果test1_hpp的范围是整个应用,据我了解,只有一个include test1.hpp成功。因为一旦包含,就定义了test1_hpp。

你的假设是正确的。如果你在你的 header 中使用 #ifndef 守卫,test1.hpp 第一次被 pre-processor 包含在你的应用程序中时,test1_hpp 将被定义并将允许将代码包含在您的 header 中。在 test1.hpp 的未来包含中,代码将不会是 re-included 感谢守卫。

这在很大程度上是必要的,以防止在项目的多个文件中包含 header 时出现双重定义,并遵守 one definition rule.

test2.hpp and test.hpp both #include test1.hpp. If the scope of test1_hpp is the whole application, as far as I understand, there can only one include test1.hpp success. Because once included, test1_hpp is defined.

编译器在 翻译单元(思考:单个 .cpp 文件)而不是整个应用程序(思考:可执行文件)上工作。你所说的"the scope of the pre-compiler define"就是当前的翻译单元。在您的示例中,test1.hpp 中的 // some declarations 部分在直接或间接包含 test1.hpp 的每个 CPP 中将是 visible/processed,即在所有 test1.cpp 中(直接), test2.cpp, test3.cpp(间接地,通过 both #include test1.hpp)。

#ifndef test1_hpp 是一种常见的习惯用法,用于防止在同一 翻译单元中多次无意中包含同一头文件 - 请参阅示例 "Use of #include guards" on Wikipedia .