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

#ifndef HELLOWORLD_H_
#define HELLOWORLD_H_

class HelloWorld {
public:
	HelloWorld();
	virtual ~HelloWorld();
};

#endif /* 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

class HelloWorld {
public:
	HelloWorld();
	virtual ~HelloWorld();
};

myhello.h

#include "HelloWorld.h"

HelloWorld.cpp

#include "HelloWorld.h"
#include "myhello.h"

HelloWorld::HelloWorld() {
}

HelloWorld::~HelloWorld() {
}

main.cpp

#include <iostream>
#include "HelloWorld.h"
using namespace std;

int main() {
    HelloWorld h;
	return 0;
}

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

g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/HelloWorld.d" -MT"src/HelloWorld.d" -o"src/HelloWorld.o" "../src/HelloWorld.cpp"

It will not compile and give errors like

In file included from ../src/myhello.h:1:0,
                 from ../src/HelloWorld.cpp:2:
../src/HelloWorld.h:2:7: error: redefinition of ‘class HelloWorld’
 class HelloWorld {
       ^
In file included from ../src/HelloWorld.cpp:1:0:
../src/HelloWorld.h:2:7: error: previous definition of ‘class HelloWorld’
 class HelloWorld {
       ^
make: *** [src/HelloWorld.o] Error 1

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

#ifndef HELLOWORLD_H_
#define HELLOWORLD_H_

class HelloWorld {
public:
	HelloWorld();
	virtual ~HelloWorld();
};

#endif /* HELLOWORLD_H_ */

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

class HelloWorld {
public:
	HelloWorld();
	virtual ~HelloWorld();
};

#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