Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
584 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...