Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

g++ - How can I compile CUDA code then link it to a C++ project?

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.

Here are my questions:

  1. How do I use nvcc to compile into a cubin file or a ptx file? Don't I need a -c or something?
  2. Which file type do I want to use?
  3. What are the g++ commands to correctly compile and link the project together?

Assume the following:

  1. I have a file called "main.cpp" that has a main function in it and includes cuda.h.
  2. I have another file called "cudaFunc.cu" that has CUDA code in it. Let's say, for instance, that I want to add two integer arrays that exist in main.cpp.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...