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

时间:2016-02-03 03:19:55

标签: c++ precompile

Is the scope of the pre-compiler define the file where it defined? for example:

three files :

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

An within test1.cpp:

#ifndef test1_hpp
#define test1_hpp

// some declarations

#endif 

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.

2 个答案:

答案 0 :(得分:1)

  

test2.hpp和test.hpp都#include test1.hpp。如果test1_hpp的范围是整个应用程序,据我所知,只有一个包含test1.hpp成功。因为一旦包含,就定义了test1_hpp。

编译器适用于whole application(想想:个人.cpp文件)而不是the scope of the pre-compiler define(想想:可执行文件)。你称之为// some declarations的是当前的翻译单元。在您的示例中,test1.hpp中的test1.hpp部分将在包含test1.cpp的每个CPP中直接或间接显示/处理,即在所有test2.cpp中直接显示(直接), test3.cppboth #include test1.hpp(间接地,通过#ifndef test1_hpp)。

ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS ); context.setContextPath( "/" ); context.addEventListener( new EnvironmentLoaderListener() ); // Add root ShiroFilter, all remaining filters and filter chains are defined in shiro.ini's [urls] section. FilterHolder filterHolder = new FilterHolder( new ShiroFilter() ); ServletHolder servletHolder = new ServletHolder( new MockServlet() ); EnumSet<DispatcherType> types = EnumSet.allOf( DispatcherType.class ); context.addFilter( filterHolder, "/*", types ); context.addFilter( new FilterHolder( new TestFilter() ), "/*", types ); context.addServlet( servletHolder, "/*" ); 是一种常见的习惯用法,可以防止在同一个翻译单元中多次无意中包含相同的头文件 - 例如参见Use of #include guards

答案 1 :(得分:0)

Your assumption is correct. If you use the #ifndef guard in your header, the first time that test1.hpp is included in your application by the pre-processor, test1_hpp will be defined and will allow the inclusion of the code in your header. In future includes of test1.hpp, the code won't be re-included thanks to the guard.

This is needed, in most part, to prevent double definitions upon including the header in multiple files of your project, and comply with the one definition rule.