More C++ Idioms/Include Guard Macro

Include Guard Macro
edit

Intent edit

To allow inclusion of a header file multiple times.

Also Known As edit

Motivation edit

Including the same header file more than once in the same compilation unit can lead to the violation of a basic rule of C++: One Definition Rule (ODR). A header may get included multiple times because of direct and indirect inclusion.

Solution and Sample Code edit

Include Guard macro idiom is an old idiom, which is also applicable in a C program. It uses simple #define to allow the inclusion of a header file multiple times in a compilation unit. The idiom ensures that after preprocessing the guarded content of the header file is only seen once by the compiler. More precisely, the compiler gets to see the guarded content where the header file gets included for the very first time. The following macros are put at the very beginning and at very end of a header file:

#ifndef MYHEADER_H_ // beginning
#define MYHEADER_H_ 
...
#endif // MYHEADER_H_ // end

Note:
Programmers often have their include guard macros start with one or more underscores, followed by uppercase letters, even though such identifiers are officially reserved for the implementation of the compiler and the Standard Library, according to the C++ Standard (ISO/IEC 14882:2003).

Some compilers support

#pragma once

as an efficient alternative to include guards. It does not require to open the header file more than once, unlike traditional include guard macro in some compilers. On many modern compilers like GCC4 or MSC++2008 #pragma once will not give better compile time performance as they recognize header guards.

Known Uses edit

Virtually all header files in the world!

Related Idioms edit

References edit

#pragma once in Wikipedia.