Include-Guard

The include guard or include guard is a programming technique to solve in C and C is the problem of multiple integration.

This problem occurs if, within a translation unit several times the same header file is included. This happens usually unintentionally, for example if a plurality of header files using the same library.

For example a multiple integration

/ / A.H const int M = 123;   class A {/ * ... * /};

/ / B.h # include " A.H "   class B: public A {/ * ... * /}; In the main program, both the class A and B will now be used:

/ / Program.cpp # include " A.H " # include " B.h "   int main () {/ * ... * /} The program is flawed, because the class A is defined twice: The first definition takes place when including the header file Ah in line 2 The second definition is because the header file Bh, which is included in line 3, in turn integrates Ah. The class ( and possibly other variables) from that file has already been defined previously, which leads to an error.

Solution with preprocessor macros (# ifndef )

The # ifndef wrapper is the traditional and C- compliant approach. The problem of multiple integration is achieved by defining a unique preprocessor macros in the first time you use the header file. Was already defined the macro, the following definitions of the header will be skipped:

/ / A.H # ifndef _A_H_ # define _A_H_   class A {/ * ... * /};   # endif / * _A_H_ * / In the above example causes that upon initial integration of Ah ( from program.cpp ) the macro _A_H_ is not yet defined, the preprocessor and passes through the definitions. In the second integration ( from Bh) the macro is already defined and the preprocessor skips the # ifndef ... # endif block.

Because macros exist in the global namespace, it can result in problems when attempting to use the same name elsewhere. This can be prevented by establishing naming conventions though, it does not solve the problem yet.

The CPP, the preprocessor of the GCC, such constructs automatically detects remembers the appropriate files and skips them in again, embedding.

Solution through language extensions (# pragma once )

Both the Microsoft C / C compiler and the GCC now support language extension # pragma once. This also ensures that a ( header ) file is included only once, except that at a higher level (directly on the preprocessor ) and is not performing macros in the global namespace in.

To use it is sufficient within the header file, the statement # pragma once inserted:

/ / A.H # pragma once   class A {/ * ... * /}; Especially in portable code must be kept in mind that this is a compiler - specific extension that is not supported by any C / C compiler.

380172
de