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

(Last Updated On: November 3, 2016)

Answer: include guards in header file in C, C++ is used to avoid compiler error i.e. redefinition of function, variable or class. #include guards also know as header guards technique are heavily used in C and C++ projects that have multiple headers and source files. In fact, include guards prevent inclusion of a header file more than once in a c, c++ program. So, we cannot get redefinition compiler error.

It 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 below example, in which A.h header file contains declaration and definition of function func(). And we have included “A.h” header file in “B.h” and also in “main.c” as in B.h , 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().

//B.h – header file

//test – main.c

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, compiler will not flash any error because compiler will check if it is already defined. If 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

 

NOTES: In 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 best practice that saves time resolving errors.