CUDA Thrust跨.cu/.cpp共享host_vector链接错误求解决方案
CUDA 12.6+ Thrust host_vector 跨编译单元链接错误问题
近期CUDA Toolkit的Thrust组件更新后,host_vector类被添加了编译时CUDA架构标签,导致nvcc编译的.cu文件与g++编译的.cpp文件链接时,即便仅使用纯主机端的host_vector对象,也会触发未定义引用错误。我们的大型项目中有大量.cpp文件依赖Qt的moc工具,无法全部改用nvcc编译。
复现环境
Ubuntu 20.04.6 LTS + CUDA 12.6
复现代码
Main.cpp
#include <cuda_runtime.h> #include <thrust/host_vector.h> bool cudaFunc(thrust::host_vector<int> &vec); int main() { thrust::host_vector<int> vec; cudaFunc(vec); }
cudaFunc.cu
#include <cuda_runtime.h> #include <thrust/host_vector.h> bool cudaFunc(thrust::host_vector<int> &vec) { return true; }
编译命令
/usr/local/cuda/bin/nvcc -c cudaFunc.cu g++ -I /usr/local/cuda/include -L /usr/local/cuda/targets/x86_64-linux/lib main.cpp cudaFunc.o -lcudart -ldl
错误信息
/usr/bin/ld: /tmp/cc5fFAJC.o: in function `main': main.cpp:(.text+0x30): undefined reference to `cudaFunc(thrust::THRUST_200500___CUDA_ARCH_LIST___NS::host_vector<int, std::allocator<int> >&)' collect2: error: ld returned 1 exit status
注:该场景在Ubuntu 20.04 + CUDA 12.3下可正常链接。
尝试使用cccl-2.6.1编译
使用第三方CCCL库编译后问题依旧:
编译命令:
/usr/local/cuda/bin/nvcc -c -Icccl-2.6.1/thrust -Icccl-2.6.1/libcudacxx/include -Icccl-2.6.1/cub cudaFunc.cu g++ -Icccl-2.6.1/thrust -Icccl-2.6.1/libcudacxx/include -Icccl-2.6.1/cub -I/usr/local/cuda/include main.cpp cudaFunc.o -L/usr/local/cuda/targets/x86_64-linux/lib -lcudart -ldl
错误信息:
/usr/bin/ld: /tmp/cc966x8Y.o: in function `main': main.cpp:(.text+0x30): undefined reference to `cudaFunc(thrust::THRUST_200601___CUDA_ARCH_LIST___NS::host_vector<int, std::allocator<int> >&)' collect2: error: ld returned 1 exit status
临时解决方案
通过自定义命名空间包裹Thrust对象,将项目中所有thrust::host_vector替换为mgxthrust::host_vector。需在引入任何Thrust头文件前,在头文件中添加以下代码:
namespace mgx_thrust { namespace thrust {} } #define THRUST_WRAPPED_NAMESPACE mgx_thrust namespace mgxthrust = mgx_thrust::thrust;
现寻求更优的解决方案。
内容的提问来源于stack exchange,提问作者RichardSmithLab
相关产品推荐
相关产品推荐

