c++ - nvcc 编译器将静态 constexpr 识别为设备代码中未定义

标签 c++ cuda constexpr nvcc

这个问题是this one的后续问题.
它是关于 nvcc 编译器将 static constexpr 类变量识别为设备代码中未定义的,如果变量是 odr-used。但是,我找不到它为什么不起作用的原因。 错误信息是:

error: identifier "Tester<int> ::ONE" is undefined in device code

编译为

nvcc -std=c++11 -ccbin=/usr/bin/g++-4.9 -arch=sm_30 main.cu

nvcc 编译器版本为 release 8.0, V8.0.26

#include <iostream>
#include <cstdlib>

#ifdef __CUDACC__
    #define HD __host__ __device__
#else
    #define HD
#endif


HD void doSomething(const int& var ) {};

template<typename T> class Tester
{
public:
    static constexpr int ONE = 1;

    HD void test()
    {
        doSomething( ONE );
    }
};
template<typename T> constexpr int Tester<T>::ONE;


int main()
{
    using t = int;

    Tester<t> tester;
    tester.test();

    return EXIT_SUCCESS;
}

问题不是关于修复这个特定代码(这将通过按值传递 var 而不是 const 引用来完成 - 至少编译器不再提示,尽管它是一个 odr-使用,不是吗?)。
问题是,这是否是 nvcc 编译器的错误,或者如果有充分的理由,为什么这不起作用(我没有在 NVIDIA 页面上找到任何提示......) .

最佳答案

我认为这段摘自 E.2.13. Const-qualified variables CUDA 文档部分解释说:

Let 'V' denote a namespace scope variable or a class static member variable that has const qualified type and does not have execution space annotations (e.g., __device__, __constant__, __shared__). V is considered to be a host code variable.

The value of V may be directly used in device code, if:
  • V has been initialized with a constant expression before the point of use, and
  • it has one of the following types:
    • builtin floating point type except when the Microsoft compiler is used as the host compiler,
    • builtin integral type.

Device source code cannot contain a reference to V or take the address of V.

我认为您的代码违反了最后一句话 - 您的代码包含引用。

关于c++ - nvcc 编译器将静态 constexpr 识别为设备代码中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39771489/

相关文章:

c++ - 高效地构建总面积表

c++ - 在 C++ Builder XE2 中重命名 VCL Form 类

c++ - 如何在 QHBoxLayout 左、中、右对齐子项

CUDA + 使用 C 计算 int 元素出现次数

c++ - 自 c++17 以来,复制省略不需要复制或移动构造函数的存在和可访问性

python - PyCUDA:设备代码中的 Pow 尝试使用 std::pow,失败

python - 如果我通过conda安装tf,是否需要手动安装tensorflow-gpu的CUDA驱动

c++ - 为什么我收到此错误 : constexpr' is not valid here

c++ - 模板函数参数显式类型声明

c++ - 如何在编译时初始化一个 float 组?