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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With