Question

I have been using guards in the header files for a while and the only reason I understand why they are used is to enable a single inclusion of this ( header file having guards under consideration ) while compilation.

I want to know if there are any other reasons of using the header guards and why are they not used in the .c files and what happens if the guards are used for .c files also ?

Ans. collected from the responses below.

Generally all the definitions goes into the .c file and the header files (.h files) include all the declarations. Its not a good practice to include .c files.

In order to associate with only one inclusion of the declarations made available to the .c file while compiling that is specific to a translation unit (therefore, if there are two or more libraries that needs to be linked; i.e., we have two or more translation units); the header guards help in including the header file ONLY ONCE.

This so happens because of the preprocessor stage even before the files compiled to get an object (.o extension) file. The preprocessor stage replaces entire macros and includes with relevant data, which allows inclusion of your .h file ONLY once.

Was it helpful?

Solution

What the header guards are doing is not to prevent multiple inclusion in a project, but in a single translation unit only.

For example, lets say you have two header files, a.h and b.h. The header file b.h includes a.h, and then both a.h and b.h is included in the source file s.c. Without header guards the file a.h will be included twice, which can cause errors. If the header files had header guards then the file a.h would only be included once.

You don't need header guards in source files because usually you don't include them in other files.

OTHER TIPS

The header guards primary purpose as you mentioned is to avoid duplicate inclusion.

Consider the following example

you have the following header files in your compilation unit

example_1.h
example_2.h (includes example_1.h)

In a 'C' file you include 'example_1.h' and 'example_2.h' the statement (macro )

'#include example_1.h' will get executed twice.

When you add the line

#ifdef EXAMPLE_1
#define EXAMPLE_1


#endif

to example_1.h you are telling you compile system when you encouter #include example_1.h the very first time,define a macro (this macro is local to your build system) which indicates to me that I have already included example_1.h.The next time I encouter #include example_1.h I will see that EXAMPLE_1 is indeed defined in the build system and skip over.

It seems a trivial thing for the small example but in large projects with hundreds of files this is indeed a very useful feature.And since .c files don't get include by other files it doesn't really make sense to include them under .c files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top