Thursday, October 25, 2007

Making Sure a Header File Gets Included Only Once

#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.
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++ cookbook]
--
#ifndef FOO_H_INCLUDED_
#define FOO_H_INCLUDED_
// … contents of the file …
#endif


Observe the following rules when defining include guards:
  • Use a unique guard name: Make sure it is unique at least within your application. We used a popular convention above; the guard name can include the application name, and some tools generate guard names containing random numbers.
  • Don't try to be clever: Don't put any code or comments before and after the guarded portion, and stick to the standard form as shown. Today's preprocessors can detect include guards, but they might have limited intelligence and expect the guard code to appear exactly at the beginning and end of the header.
Avoid using the obsolete external include guards advocated in older books:
#ifndef FOO_H_INCLUDED_ // NOT recommended
#include "foo.h"
#define FOO_H_INCLUDED_
#endif

--Coding 101(ch. 24)

No comments:

Post a Comment