-4

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.

Jorge Torres
  • 1,426
  • 12
  • 21

2 Answers2

1

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.

The compiler works on translation units (think: individual .cpp files) not the whole application (think: executable). What you call "the scope of the pre-compiler define" is the current translation unit. In your example, the // some declarations part in test1.hpp would be visible/processed in each of the CPPs that include test1.hpp directly or indirectly i.e. in all of test1.cpp (directly), test2.cpp, test3.cpp (indirectly, via both #include test1.hpp).

The #ifndef test1_hpp is a common idiom to prevent inadvertent inclusion of the same header file multiple times within the same translation unit - see for example "Use of #include guards" on Wikipedia.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
dxiv
  • 16,984
  • 2
  • 27
  • 49
  • I am sorry. I do not get it. The purpose c++ retain header guards precompilie is to avoid adding the declaration again. I have no duobt about this situation.It is the other secene that two different file both include one header once,If the variable defined by #define has global scope, The code will not excute on the other file because the variable has defined.The actual result is I can use in both files, but I do not know how that happens. – malin.llvision Feb 04 '16 at 03:49
  • @malin.llvision `It is the other secene that two different file both include one header once,If the variable` Sorry, not sure what you mean by that. A macro #define'd while compiling file1.cpp has no effect whatsoever on the compilation of file2.cpp. – dxiv Feb 04 '16 at 03:56
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.

Jorge Torres
  • 1,426
  • 12
  • 21
  • In the first place ,thank you very much. If the second time when #Include "test1.hpp" will not excute, how did the others get the interface? – malin.llvision Feb 04 '16 at 03:53