Purpose of Header guards

ckv picture ckv · Jun 5, 2010 · Viewed 9.5k times · Source

In C++ what is the purpose of header guard in C++ program.

From net i found that is for preventing including files again and again but how do header guard guarantee this.

Answer

Stephen C picture Stephen C · Jun 5, 2010

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 a header file to #include other header files without worrying that this might cause some declarations to be included multiple times.


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.