I’m a bit confused about object files that contain headers. I don’t see how header guards can protect you if they’re included in multiple object files.
For instance:
main.o <- main.cpp class.h
class.o <- class.cpp class.h
main.exe <- main.o class.o
Wouldn’t each object file contain class.h thereby making the executable have two copies of it?
Object files don’t contain headers; they contain the output of the
compiler. But the point you raise is valid: anything in the header may
be duplicated several times in the final code. Roughly speaking, we can
distinguish two categories:
Declarations that don’t create anything which might end up in the
compiler output: things like typedef’s, or for that matter, templates
and class definitions. The standard allows duplicate definitions,
provided that they’re all “identical”.
Declarations that you’re not allowed to duplicate, and which
shouldn’t be in a header. Things like variables and functions.
In practice, it’s a bit more complex, a template may be instantiated
over the same type in several different sources, and the instantiation
of a template may be a function. Or the compiler may fail to inline an
inline function. The usual way of dealing with this is for the compiler
to generate the function in each translation unit, and for the linker to
throw out the duplicates. (In fact, most linkers don’t check whether
they really are duplicates. They just throw out all but one, chosen
more or less randomly.)