gpt4 book ai didi

c++ - 如何在 cpp 和 cuda 模块中使用 cuda 类头文件

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:56 25 4
gpt4 key购买 nike

我正在尝试在我的设备中创建 Color 对象。这是我所拥有的简化版本:

Color.hpp 中:

class Color { 
public:
Color(){}
float r, g, b;
// other functions
}

test.cu 中:

__global__ void runCuda(){
Color c = Color();
}

int main() {
runCuda<<<1,1>>>()
}

这给了我一个错误说

calling a host function from a global function is not allowed

所以这很好。我只需要在 Color(){} 函数前面添加 __host__ 和 __device__ 。

但随后出现以下错误:

host does not name a type

据我所知,这是因为我没有使用 nvcc 编译它。问题是我正在使用 CMake 来构建我的项目。我不太确定它是如何做到的,但它似乎是用 c++ 编译器编译 .cpp 文件,用 nvcc 编译器编译 .cu 文件。

但在我的设备中,我想创建 Color 对象。有没有办法在我的 CMakefile 或我的代码中解决这个问题?或者我是否需要为所有现有类创建一个 cuda 版本?

最佳答案

像这样的东西应该可以工作:

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

class Color {
public:
CUDA_HOSTDEV Color(){}
float r, g, b;
// other functions
};

当您的 hpp 文件包含在 .cu 文件中时,__CUDACC__ macro将被定义。当它包含在 .cpp 文件中时(nvcc 将其交给主机编译器),宏将不会被定义。

关于c++ - 如何在 cpp 和 cuda 模块中使用 cuda 类头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com