Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"static const int" causes linking error (undefined-reference)

I am baffled by the linker error when using the following code:

// static_const.cpp -- complete code
#include <vector>

struct Elem {
    static const int value = 0;
};

int main(int argc, char *argv[]) {
    std::vector<Elem> v(1);
    std::vector<Elem>::iterator it;

    it = v.begin();
    return it->value;
}

However, this fails when linking -- somehow it needs to have a symbol for the static const "value."

$ g++ static_const.cpp 
/tmp/ccZTyfe7.o: In function `main':
static_const.cpp:(.text+0x8e): undefined reference to `Elem::value'
collect2: ld returned 1 exit status

BTW, this compiles fine with -O1 or better; but it still fails for more complicated cases. I am using gcc version 4.4.4 20100726 (Red Hat 4.4.4-13).

Any ideas what might be wrong with my code?

like image 232
hrr Avatar asked Apr 01 '11 01:04

hrr


1 Answers

If you want to initialize it inside the struct, you can do it too:

struct Elem {
    static const int value = 0;
};

const int Elem::value;
like image 57
karlphillip Avatar answered Oct 07 '22 13:10

karlphillip