Look at this code:
#include <map>
#include <string>
struct Foo {
static const std::map<std::string, int> bar;
};
struct A {
static const int X = 0;
};
const std::map<std::string, int> Foo::bar = {{"foo", A::X}};
int main() {
}
When compiled with -O0
with either Clang or GCC it gives an undefined reference error:
undefined reference to `A::X'
(See Godbolt)
However if you compile with -O3
, or if you change the std::string
to int
, or if you move the definition of X
outside the class like this
struct A {
static const int X;
};
const int A::X = 1;
then it compiles fine!
What's going on here?