Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling CUDA code from regular C++ code - sorting out the extern "C"

I am trying to call a CUDA (host) function 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 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 in this method of integration of C++ and CUDA?

like image 762
Hardik Avatar asked Nov 04 '10 17:11

Hardik


1 Answers

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

Alternatively, but pointlessly, you could add the same declaration to the cuda.cu file.

To elaborate a little, nvcc is a wrapper which splits 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 meant that you needed to put extern "C" on the delcarations when calling from C++. Returning to the present time, nvcc defaults to C++ for host code which means you shouldn't need those externs any more (unless the rest of your host code is in C of course).

like image 195
Tom Avatar answered Oct 23 '22 09:10

Tom