如果我尝试在同一项目中使用 stl 矢量和 CUDA 推力矢量,为什么会出现链接错误

Why there is linking error if I try to use stl vector and CUDA thrust vector in the same project?

本文关键字:CUDA 为什么 错误 链接 项目 如果 stl      更新时间:2023-10-16

如果我尝试在同一项目中使用 stl 矢量和 CUDA 推力矢量,为什么会出现链接错误?

文件1.h

#include <vector>
using namespace std;
class A{
public:
    A();
    vector<int> vec;
//....
};

File2.cu

#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
void ComputeDer(){
thrust::device_vector<int> Dh(4);
thrust::host_vector<int> H(4);//only host_vector can compile.
}

如果我注释掉其中一个向量声明,则可以编译代码,但如果两者都存在,则会出现以下错误:

1>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::~basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(void)" (??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ) already defined in ComputeDer.cu.obj
1>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(char const *)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@PBD@Z) already defined in ComputeDer.cu.obj
1>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@ABV01@@Z) already defined in ComputeDer.cu.obj
1>msvcprtd.lib(MSVCP90D.dll) : error LNK2005: "public: char const * __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::c_str(void)const " (?c_str@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEPBDXZ) already defined in ComputeDer.cu.obj

谁能给我任何想法?

最有可能的问题在

using namespace std;
使用它

根本不是好的做法,但如果您选择使用它,至少将其放入使用它的.cpp文件中,而不是放在头文件中。通过将其放在头文件中,您可以将其推断到包括该头文件在内的所有文件。