Search code examples
c++header-filesredefinition

Why doesn't including 1 header file into two CPP files cause a redefinition error?


Let's say I have a header file like this:

ABC.h

class A {
    int d = 5;
    int e = 6;
};

Then I include ABC.h into two source CPP files. Wouldn't then when the linker link the compilation units together, I would end up with 2 definition of class A? But then why doesn't the linker complain when I test out this experiment? I am confused.

I am compiling using Visual Studio 2017.


Solution

  • There are two possible kinds of answer to this question.

    1. There is no error because otherwise it would be impossible to produce any useful program. Such repeated class definitions in multiple translation units are normal and expected in every program. So the language is defined in such a way that it just works.
    2. There is no error because this class definition doesn't create any global symbols that may cause multiple definition errors. Global symbols are normally created by definitions of non-inline variables or functions with external linkage. There are no such definitions in this header file. Classes and their non-static members have no linkage.