This article introduces the role of macro definitions used together by #ifndef, #define, and #endif.
In header files, we often see macro definitions used together with #ifndef, #define, and #endif in header files.
For example, in the header file xxx.h (this style is available for reference):
#ifndef __XXX_H__ #define __XXX_H__ #include <iostream> // other code ... #endif
The function of using #ifndef, #define, #endif to combine macro definitions is to prevent repeated inclusion and compilation of header files.
For example, there are now 4 files: main.cpp, fileA.h, fileB.h, and fileC.h. The inclusion relationships of these files are as follows:
In fileC.h, there is the definition of nTest. In this case, when compiling main.cpp, the system will report an error, prompting nTest to redefine, and the error message is as follows:
This problem can be well avoided by using the #ifndef, #define, #endif macro definition combination introduced in this article. The modified fileC.h code is as follows:
#ifndef __FILEC_H__ #define __FILEC_H__ #include <iostream> using namespace std; int nTest = 1; #endif