When I have the following code in A.cpp and B.cpp there is no warning or error generated, but Initializer::Initializer() in B.cpp gets called twice while the one in A.cpp doesn’t get called.
static int x = 0;
struct Initializer
{
Initializer()
{
x = 10;
}
};
static Initializer init;
Since this is breaking the one definition rule and causing undefined behavior I think this is perfectly normal. However, when I move the constructor definition outside of the class declaration in either or both files, like this:
static int x = 0;
struct Initializer
{
Initializer();
};
Initializer::Initializer()
{
x = 10;
}
static Initializer init;
The linker suddenly becomes smart enough to error and say one or more multiply defined symbols found. What changed here and why did it matter? I would have thought the linker should always be able to detect ODR breakage – what are the cases when it can’t?
Someone correct me if I’m wrong, but my theory is that when you have templated code (where the definitions are always in headers) you end up with duplicated definitions in many compilation units. They happen to all be identical, so it doesn’t matter if the linker just chooses one and orphans the others, but it can’t error that there are multiple definitions or templates wouldn’t work.
Your second example has an obvious and easy to diagnose violation of the one definition rule. It has two definitions of a non-inline function with external linkage. This is easy for the linker to diagnose as the violation is obvious from the names of the functions contained in the object files that it is linking.
Your first example breaks the one definition rule in a much subtler way. Because functions defined in a class body are implicitly declared
inlineyou have to examine the function bodies to determine that the one definition rule has been violated.For this reason alone I am not surprised that your implementation fails to spot the violation (I didn’t the first time around). Obviously the violation is impossible for the compiler to spot when looking at one source file in isolation but it may be that the information to detect the violation and link time is not actually present the object files that are passed to the linker. It is certainly beyond the scope of what I’d expect a linker to find.