"static const int"导致链接错误(未定义引用)

hrr*_*hrr 14 c++ static gcc const stdvector

使用以下代码时,我对链接器错误感到困惑:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,这在链接时失败 - 不知何故,它需要有一个静态const"值"的符号.

$ 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
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这与-O1或更好的编译很好; 但对于更复杂的情况,它仍然失败.我使用的是gcc版本4.4.4 20100726(Red Hat 4.4.4-13).

任何想法我的代码可能有什么问题?

kar*_*lip 8

如果你想在struct中初始化它,你也可以这样做:

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

const int Elem::value;
Run Code Online (Sandbox Code Playgroud)


jon*_*sca 5

试着把它写成

struct Elem {
    static const int value;
};

const int Elem::value = 0;

etc
Run Code Online (Sandbox Code Playgroud)

.

  • 我应该让自己更清楚。我试图向任何阅读您回答的人指出 - 尽管完全正确 - 在某些情况下这不起作用。例如,如果你想在 switch 中使用 `value` 作为标签,比如 `switch(x) { case value: break; }` (2认同)