I know people recommend including header guards in header files, to prevent header files contents from being inserted by the pre-processor into the source-code files more than once.
But consider the following scenario:
Let’s say I have the files main.cpp , stuff.cpp, and commonheader.h, with the .h file having its header guards.
If either .cpp files tries to include commonheader.h more than once, then the preprocessor
will stop that from happening, and after compiling to object code we get,
main.o containing the contents of commonheader.h exactly once.
stuff.o containing the contents of commonheader.h exactly once.
Note that the contents of commonheader, have been repeated across the files, but not within the same .o file.
So what happens during the linking step? Since the .o files are being fused into an exectuable
we will have to ensure for a second time that the contents of commonheader are not being repeated. Does the compiler take care of that? If not, wouldn’t that be a problem when we are dealing with huge header files, giving rise to code repetition across files and leading to large executable sizes.
If I am making some conceptual mistake anywhere in the question, please correct me.
Typically your header file should not actually define any symbols, it should just declare them. So commonheader.h would look like this (omitting the include guards):
In that case, there is no problem. If you call
commonFunc1inmain.cppandstuff.cpp, bothmain.oandstuff.owill know they want to link against a symbol calledcommonFunc1and the linker will try to find that symbol. If the linker doesn’t find the symbol, you get an undefined reference error. The actual definition ofcommonFunc1needs to be in some cpp file.If you really want to define functions in your header file, use
staticso that the linker does not see them. So your commonheader.h could look like:In this case, the linker does not know about
commonFunc1and no errors will occur. This could increase the executable size though; you’ll probably end up with two copies of the code forcommonFunc1.