“静态常量 int"导致链接错误(未定义引用)

2022-01-23 00:00:00 gcc static constants c++ stdvector

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

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;
}

但是,这在链接时会失败――不知何故,它需要一个符号来表示静态 const 值".

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

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

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?

推荐答案

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

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;

相关文章