2.1. Making Sure a Header File Gets Included Only Once

Problem

You have a header file that is included by several other files. You want to make sure the preprocessor scans the declarations in the header file no more than once.

Solution

#define a macro in your header file, and include only the contents of the header file if the macro hasn’t already been defined. You can use this combination of the #ifndef, #define, and #endif preprocessor directives, as I did in Example 2-1:

#ifndef MYCLASS_H_  _ // #include guards
#define MYCLASS_H_  _

// Put everything here...

#endif // MYCLASS_H_  _

When the preprocessor scans this header file, one of the first things it will encounter is the #ifndef directive and the symbol that follows. #ifndef tells the preprocessor to continue processing on the next line only if the symbol MYCLASS_H_ _ is not already defined. If it is already defined, then the preprocessor should skip to the closing #endif. The line following #ifndef defines MYCLASS_H_ _, so if this file is scanned by the preprocessor twice in the same compilation, the second time MYCLASS_H_ _ is defined. By placing all of your code in between the #ifndef and #endif, you ensure that it is only read once during the compilation process.

Discussion

If you don’t use this technique, which is called using include guards , you’ve probably already seen “symbol already defined” compilation errors that result from not taking a protective measure against multiple definitions. C++ does not allow you to define ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.