how to prevent multiple inclusions of header files? why it is necessary to prevent multiple inclusion of header files? what are header files. Header file is a file containing macros and declaration to be shared among source file. Usually header files named as #include <HelloWorld.h>. #include is preprocessor directive which informs compiler to scan HelloWorld.h as input. Let us below sample header file.

Sample HelloWorld.h

The guard  #ifndef HELLOWORLD_H_

                  #define HELLOWORLD_H_

                  ……………..

                 ……………….

                  #endif

prevents multiple inclusion of header file HelloWorld.h in others source file. This types of gaurd prevent the compiler from processing them more than once.

Let us create a problematic source code which suffers from double inclusion of header file.

HelloWorld.h

myhello.h

HelloWorld.cpp

main.cpp

Now let us compile the above program and see the error message.

It will not compile and give errors like

The error is coming because of header file HelloWorld.h. I has been included two times in our example project. To prevent from double inclusion of header file HelloWorld.h , guard it using macro like below

Now try to compile the program. it will compile successfully.

how to prevent multiple inclusions of header files using #pragma directive.

Include #prgama once to top of the header file.

#pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation. ( https://en.wikipedia.org/wiki/Pragma_once )

Ref:

https://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html




Related Contents to follow