Include guards – why to write in header files – C, C++

Answer: The include guards in header file in C, C++ is used to avoid compiler error i.e. redefinition of function, variable or class.

The #include guards (also know as header guards) technique are heavily used in the C and C++ projects that have multiple headers and source files.

In fact, the include guards prevent inclusion of a header file more than once in a c, C++ program. So, we cannot get redefinition compiler error.

It’s possible that one header file got included in multiple header or source files. If that is the case, we will get compiler error.

Include guards with example

Consider the below example, in which A.h header file contains declaration and definition of function func().

We have included “A.h” header file in “B.h” and also in “main.c” as in B.h , the requirement is to call func() inside the funcB() and also the func() call in main.c.

//A.h – header file contains declaration and definition of a function func().

void func(){
	
}

//B.h – header file

#include "A.h"

void funcB(){
	func();
}

//test – main.c

#include "A.h"
#include "B.h"

int main(){
	func();
	return 0;
}

When compiler see a of func() in main, it will go to “A.h” header file and find the definition of func() method.

Next, it will go to “B.h” and via “B.h” header file. Again it will go to “A.h” and find the definition of func() function again resulting redefinition of func() method. Hence, compiler throws an error for redefinition.

If we include a guard like below ifndef header example, the compiler will not flash any error because compiler will check if it is already defined.

If the header guard is defined  in the header file, it will return from here and skips the rest of the file on next visit.

//A.h

#ifndef __A_H__
#define __A_H__

void func(){
	
}

#endif

NOTE

In the real time large project, double inclusion of a header file happens. It could be due to copy paste of source code or unknowingly include the header file to get a function in a file etc.

Hence, using the #include guards are the best practice that saves time resolving errors in a C and C++ programming.

Related Posts