c++ - Intel vs GCC on constexpr

标签 c++ gcc intel static-members constexpr

以下代码在 Intel-2015 上编译正常,但在 gcc 4.8.3 上编译失败 谁是对的?

#include <iostream>

void f( int const& x ) { std::cout << x << std::endl; }

struct S
{
    static constexpr int ce = 42;
};

int main()
{
    f(S::ce);

    return 0;
}

g++ 错误:

/tmp/ccOIxa2V.o: In function `main':
test_constexpr.cpp:(.text+0x36): undefined reference to `S::ce'
collect2: error: ld returned 1 exit status

最佳答案

因为函数 f 接受一个引用参数,所以必须有一个 S::ce 的定义,一个引用可以在运行时指向;编译器不能只用文字 42 替换参数。所以你必须添加一个类外定义:

const int S::ce;

就像您使用非constexpr 变量一样。这会在运行时为值分配一个内存位置,供引用和其他无法在编译时计算的内容使用。

参见 this GCC bug report (其中有解释为什么它实际上不是错误的评论)以获取更多信息。

关于c++ - Intel vs GCC on constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324686/

相关文章:

c++ - 使用函数输出字符串或字符。小白

c++ - libmysqlclient.a 和 libmysqlclient_r.a 有什么区别?

Java JNI EXCEPTION_ACCESS_VIOLATION

Linux:可执行文件找不到共享库

C++将数组参数传递给函数

c++ - 使用反射在 protobuf 中设置重复字段

c++ - 错误的符号扩展 c++/qt

javascript - 英特尔 xdk : my links are not working

linux - Linux 服务器的新手,关于使用可能不同版本的 MPI 执行二进制文件

assembly - 在 x86 汇编中实现 160x100 模式