Calling CUDA code from regular C ++ code - sorting the external expression "C"

I am trying to call the CUDA function (host) from a C ++ file compiled separately:

sample.cpp C ++ file:

 extern "C" void cuda_function(int a, int b); int main(){ //statements cuda_function(23, 34); //statements } 

cuda.cu file:

 #include <cuda.h> __global__ void kernel(int a, int b) { //statements } void cuda_function(int a, int b){ //cuda_function } 

Build Commands:

 g++ -c sample.cpp nvcc -c cuda.cu nvcc -o sample sample.o cuda.o 

But this gives a linker error:

 sample.o: In function `main': sample.cpp:(.text+0x163): undefined reference to `cuda_function' collect2: ld returned 1 exit status 

What is wrong with this C ++ and CUDA integration method?

+4
source share
1 answer

You declared cuda_function() as extern "C" , but then defined it with C ++. Remove extern "C" from your delcaration and it will work.

Alternatively, but pointless, you can add the same declaration to the cuda.cu file.

To develop a bit, nvcc is a shell that breaks a file into host code and device code, and then calls the host compiler and device compiler, respectively. Back in the old days of CUDA programming, nvcc called the host compiler in "C" mode wihch, which meant that you had to put extern "C" in delcarations when called from C ++. Returning to the current time, nvcc by default uses C ++ for the host code, which means that you no longer need these externs (unless, of course, the rest of your host code is in C).

+10
source

All Articles