cpp: Once-Only Headers

1 
1 2.4 Once-Only Headers
1 =====================
1 
1 If a header file happens to be included twice, the compiler will process
1 its contents twice.  This is very likely to cause an error, e.g. when
1 the compiler sees the same structure definition twice.  Even if it does
1 not, it will certainly waste time.
1 
1    The standard way to prevent this is to enclose the entire real
1 contents of the file in a conditional, like this:
1 
1      /* File foo.  */
1      #ifndef FILE_FOO_SEEN
1      #define FILE_FOO_SEEN
1 
1      THE ENTIRE FILE
1 
1      #endif /* !FILE_FOO_SEEN */
1 
1    This construct is commonly known as a "wrapper #ifndef".  When the
1 header is included again, the conditional will be false, because
1 'FILE_FOO_SEEN' is defined.  The preprocessor will skip over the entire
1 contents of the file, and the compiler will not see it twice.
1 
1    CPP optimizes even further.  It remembers when a header file has a
1 wrapper '#ifndef'.  If a subsequent '#include' specifies that header,
1 and the macro in the '#ifndef' is still defined, it does not bother to
1 rescan the file at all.
1 
1    You can put comments outside the wrapper.  They will not interfere
1 with this optimization.
1 
1    The macro 'FILE_FOO_SEEN' is called the "controlling macro" or "guard
1 macro".  In a user header file, the macro name should not begin with
1 '_'.  In a system header file, it should begin with '__' to avoid
1 conflicts with user programs.  In any kind of header file, the macro
1 name should contain the name of the file and some additional text, to
1 avoid conflicts with other header files.
1