0
votes

1.cpp:

static struct SA {
    int m=1;
    int func() {return m;}
}g;

static void test() {
    g.func();
}

2.cpp:

static struct SA {
    int m=2;
    int func() {return m*m;}
}g;

static void test() {
    g.func();
}

(1) Is One Definition Rule violated in such case? (2) If not, then ODR is only violated once SA is referenced somewhere?

1
It's UB because struct SA is defined by a different sequence of tokens in different translation units - M.M

1 Answers

1
votes

Yes, the rule is violated. Say, if both .cpp are built in the same static library and one of them is used then it result in UB. This is because linker can't tell the difference between the two and links rather randomly. Same happens when you link several static libraries that define same symbol. Linker just assumes that those are the same.

In fact frequently linker has to throw away duplicates due to functions/class definitions in headers.

IIRC shared libraries / .dll are more resilient to this problem as only a far more limited number of symbols are exposed to the linker.

In C++20, modules are supposed to fix such issues.