“静态常量整型”导致链接错误(未定义引用)
使用以下代码时,我对链接器错误感到困惑:
// 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;
}
但是,链接时会失败——不知怎的,它需要有一个静态常量“值”的符号。
$ 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)。
有什么想法我的代码可能有什么问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你想在struct内部初始化它,你也可以这样做:
If you want to initialize it inside the struct, you can do it too:
尝试将其写为
.
Try writing it as
.
static
类成员通常应该在一个编译单元中的类外部定义(在内部声明,在外部定义)。我不记得它是如何与 const 静态整数成员的内联初始化交互的。
static
class members are generally supposed to be defined outside the class (declared inside, defined outside) in one compilation unit.I don't remember how that interacts with inline initialization of
const
static integral members.另请参阅这篇文章:本质上,问题是编译器最终会以某种方式扩展您的代码以获取 Elem::value 的地址。
Also see this post: essentially, the problem is that somehow compiler ends up expanding your code into taking the address of Elem::value.
在大多数定义类内
static const
的编译器中都可以正常工作。但某些编译器(例如 Android NDK),此类内定义会导致链接器错误。对于这种情况,我们可以使用类型化的枚举:In most of the compilers defining in-class
static const <integral type>
works fine. But some compilers like Android NDK, such in-class definitions results in linker errors. For such case, we may use the typedenum
s:为什么不直接这样做呢?
但答案是您正在声明中分配一个值。这应该适用于基本类型,例如 int,并且仅对于复杂类型(即类,例如如果您有字符串而不是 int)才需要。我在实践中发现,这取决于您使用的编译器的版本。而且,正如您所发现的,哪个优化级别。
Why not just do this?
But the answer is that you are assigning a value in the declaration. This is supposed to work for basic types such as
int
, and is only required for complex types (i.e. classes, such as if you had a string instead of int). What I have found in practice is that this is hit or miss depending on what version of what compiler you are using. And, as you found out, which optimization level.