I know this is a common question but I still can't fully get my head around it.
In a C or C++ program generated from multiple different source and header files, will each header file be only included once in the entire code when the header guards are used?
Someone told me previously that a header file (with include guards) will get included only once in one translation unit but multiple times in the entire code. Is this true?
If it gets included only once throughout the entire code, when one file wishes to include it and the preprocessor detects that it has already been included, how does that file that wishes to use it know whereabouts in the code it was previously included ?
A "header file" is actually inserted by the pre-processor before compilation starts. Just think of it as just "replacing" its
#include
directive.The guard ...
... is executed after the replacement. So, the header may actually be included multiple times, but the "guarded" part of the text is only passed to the compiler once by the preprocessor.
So, if there are any code-generation definitions in the header, they will - of course - be included into the object file of the compilation unit (aka "module"). If the same header is
#include
ded in multiple modules, these will appear multiple times.For
static
definitions, this is no problem at all, as these will not be visible beyond the module (aka file scope). For program-global definitions, that is different and will result in "multiple definitions" error.Note: this is mostly for C. For C++, there are significant differences, as classes, etc. add additional complexity to what/when multiple global objects are allowed.