Purpose of Header guards

The guard header (or more conventionally “include guard”) is to prevent problems if header file is included more than once; e.g.

#ifndef MARKER
#define MARKER
// declarations 
#endif

The first time this file is #include-ed, the MARKER preprocessor symbol will be undefined, so the preprocessor will define the symbol, and the following declarations will included in the source code seen by the compiler. On subsequent #include‘s, the MARKER symbol will be defined, and hence everything within the #ifnde / #endif will be removed by the preprocessor.

For this to work properly, the MARKER symbol needs to be different for each header file that might possibly be #include-ed.

The reason this kind of thing is necessary is that it is illegal in C / C++ to define a type or function with the same name more than once in a compilation unit. The guard allows you to #include a header file without worrying if has already been included. Without the guard, multiple inclusions of the same header file would lead to unwanted redeclarations and compilation errors. This is particularly helpful when header files need to #include other header files.


In short, it doesn’t prevent you from #include-ing a file again and again. Rather, it allows you to do this without causing compilation errors.

Leave a Comment