“static const int”导致链接错误(未定义参考) [英] "static const int" causes linking error (undefined-reference)
本文介绍了“static const int”导致链接错误(未定义参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下代码时,链接器错误使我感到困惑:
// 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值。
$ g ++ static_const.cpp
/ pre>
/tmp/ccZTyfe7.o: main':
static_const.cpp :(。text + 0x8e):未定义引用`Elem :: value'
collect2:ld返回1退出状态
BTW,这个编译精细与-O1或更好;但是对于更复杂的情况它仍然失败。我使用gcc版本4.4.4 20100726(红帽4.4.4-13)。
任何想法我的代码可能有什么问题?
解决方案如果你想在 struct 里初始化它,你也可以这样做:
struct Elem {
static const int value = 0;
};
const int Elem :: value;
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?
解决方案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;
这篇关于“static const int”导致链接错误(未定义参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文