【发布时间】:2015-03-18 17:20:51
【问题描述】:
我正在使用 gcc (Debian 4.4.5-8) 4.4.5。使用以下代码,我收到链接错误:
/tmp/ccOeGgC9.o:在函数
A::func()':B::CONST_B'
(.text+0x1b): undefined reference to
(.text+0x23): 对 `A::CONST_A' 的未定义引用
标题:
class A {
public:
static const int CONST_A = 10;
int func();
};
class B {
public:
static const int CONST_B = 20;
};
cpp 文件(有链接错误):
int A::func() {
bool c = true;
const int a = (c == true) ? B::CONST_B : CONST_A;
}
int main() {
return 0;
}
要修复错误,我必须编写 cpp 文件如下:
cpp 文件(工作):
int A::func() {
bool c = true;
int a = CONST_A;
a = (c == true) ? B::CONST_B : a;
}
int main() {
return 0;
}
你能解释一下为什么我不能编译第一个代码吗?
【问题讨论】:
-
我看不到您的示例如何给出链接器错误。在这种情况下,
CONST_B和CONST_A不使用 odr。 coliru.stacked-crooked.com/a/0e25fcbbc9d39dab -
我用较新版本的 gcc 进行了尝试,但没有看到链接器错误,但我只能用 gcc (Debian 4.4.5-8) 4.4.5 编译我的代码
-
@0x499602D2 这类 ODR 违规不需要诊断,因此干净的编译并不能证明代码是正确的
标签: c++