【发布时间】:2018-11-21 07:46:51
【问题描述】:
这是我的代码,a.cpp
struct int2
{
int x, y;
};
struct Foo{
static constexpr int bar1 = 1;
static constexpr int2 bar2 = {1, 2};
};
int foo1(){
return Foo::bar1; // this is ok for both clang++ and g++
}
int2 foo2(){
return Foo::bar2; // undefined reference to `Foo::bar2' in clang++
}
int main(){ std::cout << foo2().x << std::endl; return 0; }
使用clang编译,clang++ -std=c++11 a.cpp
/tmp/a-0dba90.o: In function `foo2()':
a.cpp:(.text+0x18): undefined reference to `Foo::bar2'
clang-7: error: linker command failed with exit code 1 (use -v to see
invocation)
g++ -std=c++11 a.cpp 不会发出任何错误。
我的问题是,
- 谁是正确的上述代码? clang 还是 g++?
- 为什么在 clang 中 bar2 是错误的而 bar1 是正确的?
编译器版本:g++ 5.4.0 和 clang 7.0.0
更新:该问题被标记为与another question 重复,但事实并非如此。我知道我可以在类之外添加显式定义以使其通过 clang。这个问题是关于为什么 g++&clang 之间的所有区别。
【问题讨论】:
-
int2是什么类型?它不在标准中。
-
@arorias 是的,我包含了定义。
-
@xdot: 哪个版本的clang?从 clang 3.0 开始无法在 Godbolt 上复制。 godbolt.org/z/UwjgHv
-
对我来说看起来像是一个 clang 错误,除非标准在 C++11 中被打破。
-
如果编译器根据优化级别发出错误或不发出错误,则该编译器存在错误或您的程序存在 UB。
标签: c++ c++11 one-definition-rule