Purpose of Header guards
In C++ what is t开发者_运维百科he 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.
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.
The purpose of header guards is to prevent issues where some code may appear only once per translation unit.
One example is a struct. You cannot redefine a struct even if the second definition is identical. So, if you try to compile the following:
struct foo { int x; };
struct foo { int x; };
The compiler will fail because of the redefinition.
It can be hard to guarantee you only include a header one time (this happens when headers include other headers). If your header has struct definition, this will cause the compile to fail. Header guards are the easy trick so that even if a header is included multiple times, it's contents only appear a single time.
精彩评论