More C++ Idioms/Include Guard Macro

From Wikibooks, the open-content textbooks collection

< More C++ Idioms
Jump to: navigation, search

Contents

[edit]

Include Guard Macro

[edit] Intent

To prevent inclusion of a header file multiple times.

[edit] Also Known As

[edit] Motivation

Including the same header file in same compilation unit is a problem because it violates a basic rule of C++: One Definition Rule (ODR). A header may get included multiple times because of direct and indirect inclusion.

[edit] Solution and Sample Code

Include Guard macro idiom is an old idiom, which is also applicable in a C program. It used simple #define to prevent inclusion of a header file multiple times in a compilation unit. 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

Some compiler 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.

[edit] Known Uses

Virtually all header files in the world!

[edit] Related Idioms

[edit] References

#pragma once in Wikipedia.

Personal tools
Create a book
  • Add wiki page
  • Collections help
In other languages