0

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?

5
  • Hmm it may be the same issue as in this question: stackoverflow.com/q/16957458/265521
    – Timmmm
    Commented Feb 17, 2022 at 10:02
  • 1
    You should use inline keyword if you want to initialize static data member inplace
    – Osyotr
    Commented Feb 17, 2022 at 10:06
  • Are you allowed/able to use C++17 features?
    – nada
    Commented Feb 17, 2022 at 10:07
  • If yes, you can change it like this.
    – nada
    Commented Feb 17, 2022 at 10:08
  • Yeah inline worked, thanks!
    – Timmmm
    Commented Feb 17, 2022 at 10:09

0

Browse other questions tagged or ask your own question.