2.4. Once-Only Headers
2.4 Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time.
The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this:
/* File foo. */ #ifndef FILE_FOO_SEEN #define FILE_FOO_SEEN the entire file #endif /* !FILE_FOO_SEEN */
This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional will be false, because FILE_FOO_SEEN
is defined. The preprocessor will skip over the entire contents of the file, and the compiler will not see it twice.
CPP optimizes even further. It remembers when a header file has a wrapper ‘#ifndef
’. If a subsequent