如何编译 CUDA 代码然后将其链接到 C++ 项目? [英] How can I compile CUDA code then link it to a C++ project?
问题描述
我正在寻求有关 CUDA 项目的入门帮助.我的目标是拥有一个可以在本机 g++ 编译器中编译但使用 CUDA 代码的项目.我知道我必须在 nvcc 编译器中编译我的 CUDA 代码,但据我了解,我可以以某种方式将 CUDA 代码编译成 cubin 文件或 ptx 文件.
I am looking for help getting started with a project involving CUDA. My goal is to have a project that I can compile in the native g++ compiler but uses CUDA code. I understand that I have to compile my CUDA code in nvcc compiler, but from my understanding I can somehow compile the CUDA code into a cubin file or a ptx file.
这是我的问题:
- 如何使用 nvcc 编译成 cubin 文件或 ptx 文件?我不需要 -c 什么的吗?
- 我要使用哪种文件类型?
- 正确编译和链接项目的 g++ 命令有哪些?
假设如下:
- 我有一个名为main.cpp"的文件,其中包含一个 main 函数并包含 cuda.h.
- 我有另一个名为cudaFunc.cu"的文件,其中包含 CUDA 代码.例如,假设我想添加两个存在于 main.cpp 中的整数数组.
推荐答案
我能够通过几个不同的帖子解决我的问题,包括这些帖子.不要忘记,如果您使用 64 位机器链接到 64 位库!它看起来很明显,但对于像我这样的小丑来说,这是我忘记的.这是我现在使用的 make 文件......如果你能消化这个 make 文件,你应该能够做我想做的事情,即分别编译 cuda 代码和其他 G++ 代码.另外请记住,您必须在某些版本中拥有 gcc、g++ 编译器(我使用的是 g++-4.4,它对我有用)无论如何,这里是 make 文件...
I was able to resolve my issue with a couple of different posts including these ones. Don't forget that if you are using a 64 bit machine to link to the 64 bit library! It seams kind of obvious, but for clowns like me, that is something I forgot. Here is the make file that I now use... if you can digest this make file, you should be able to do what I was trying to do which was separate compilation of cuda code and other G++ code. Also keep in mind that you have to have the gcc, g++ compilers at certain versions (I am using g++-4.4 and it is working for me) Anyway, here is the make file...
all: program
program: cudacode.o
g++ -o program -L/usr/local/cuda/lib64 -lcuda -lcudart main.cpp cudacode.o
cudacode.o:
nvcc -c -arch=sm_20 cudacode.cu
clean: rm -f *.o program
希望您能看到我做的第一件事是使用 nvcc
编译器和 编译 cudacode(已保存为
选项(另请注意,您可能需要删除 .cu
)-c-arch=sm_20
).这创建了一个 cudacode.o
.然后我使用带有 -o
选项的 g++ 编译器并链接到 lib64 库并链接 -lcuda
和 -lcudart
库以及编译我的 main.cpp
然后链接 cudacode.o
.希望这对某人有帮助!
Hopefully you can see that the first thing I do is compile the cudacode (that has been saved as a .cu
) using the nvcc
compiler and -c
option (also note that you may want to remove the -arch=sm_20
). This created a cudacode.o
. I then use the g++ compiler with the -o
option and link to the lib64 library and link the -lcuda
and -lcudart
libraries along with compiling my main.cpp
and then linking the cudacode.o
. Hope this helps someone!
这篇关于如何编译 CUDA 代码然后将其链接到 C++ 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!