Sunday, September 4, 2011

[C++]Head file management #ifndef, #endif

quoted from "C++ Primer Plus, Fifth edition" about #ifndef, #endif:


You should include a header file just once in a file. There’s a standard C/C++ technique for
avoiding multiple inclusions of header files. It’s based on the preprocessor #ifndef (for if not
defined) directive. A code segment like

#ifndef COORDIN_H_
...
#endif


means process the statements between the #ifndef and #endif only if the name COORDIN_H_ has
not been defined previously by the preprocessor #define directive.

The technique that Listing 9.1 uses is to wrap the file contents in an #ifndef:

#ifndef COORDIN_H_
#define COORDIN_H_
// place include file contents here
#endif

The first time the compiler encounters the file, the name COORDIN_H_ should be undefined. (I chose
a name based on the include filename, with a few underscore characters tossed in to create a
name that is unlikely to be defined elsewhere.) That being the case, the compiler looks at the material
between the #ifndef and the #endif, which is what you want. In the process of looking at the
material, the compiler reads the line defining COORDIN_H_. If it then encounters a second inclusion of
coordin.h in the same file, the compiler notes that COORDIN_H_ is defined and skips to the line following
the #endif. Note that this method doesn’t keep the compiler from including a file twice.
Instead, it makes the compiler ignore the contents of all but the first inclusion. Most of the standard
C and C++ header files use this guarding scheme.

No comments:

Fork me on GitHub