Why is multiple variable definition across different source files a problem, but multiple class definition across different sources is not

I am currently learning C++ (more precisely C++03) at uni, and I came across the initialization of static members. Non-constant static members should be declared inside the class, but defined outside. Moreover, they also should be declared in source files, not header files. As far as I understand, that is because if you have a myClass.h header with a myClass class in it, and A.cpp and B.cpp which include it, then you can protect yourself from multiple definition inside the same source file with include guards, but you cannot protect from myClass.h being present once in A.cpp and once in B.cpp. If you define the static member inside myClass.h, but outside myClass, then after the preprocess you will have copied the definition of the same thing both inside the global scope of A.cpp and B.cpp. The linker will "see" the global scope of B.cpp from inside A.cpp and vicecersa, so you will have multiple definitions available in a given context, which is a problem.

So my question is, if this is a problem, then how come the definition of the class myClass both in the global scope of A.cpp and B.cpp isn't one?


  • No you misunderstand the reasons. static variables that are not constexpr needs to be initialized only once as it happens at runtime. Something is really wrong if same variable is initialized twice at run-time... Thus they have to be initialized in a .cpp so that compiler/linker knows which library carries it.

    Definitions for classes, on the other hand, are compile-time definitions so linker throws away all duplicates. (This is in fact is very bad and results in poor compilation times and at times in ODR issues. Modules C++20 were developed to resolve these issues.).