ccudanvcc

How to compile C code with C headers and CUDA code?


I have a main code which uses some libraries and I been compiling it like this:

gcc importedCFile1.c importedCFile2.c mainCode.c -O3 -lm -Wall -o maincode -lrt

Now I have added CUDA code in mainCode and changed its extension to .cu... So, how can I compile the whole thing?

I tried:

nvcc importedCFile1.c importedCFile2.c mainCode.cu -o maincode 

but I got a lot of "undefined reference" to my functions in the imported C files.

To include my C files I am using:

extern "C" {
   #include "importedCFile1.h"
   #include "importedCFile2.h"
}

And ´importedCFile1.c´ is using some functions and variables declared in ´importedCFile2.c´ and ´mainCode.cu´. Like this:

extern int **se;        // Variables from mainCode  
extern int *n;          
extern int numNodes;

extern int *getVector(int n);   // Function from mainCode
extern int iRand(int high);     // Function from importedCFile2

This functions are the cause of the undefined references. What should I do?

Also, how do I add the flags I need for the C code, such as -lrt, O3, lm and Wall??

EDIT: You can find a reduced example of the problem here:

https://github.com/mvnarvaezt/cuda/tree/master/minimalExample

If you compile the mainCode.c and importedCFile.c with gcc it works fine. If you compile mainCode.cu and importedCFile.c with nvcc you will get an undefined reference to anExample() (the function in importedCFile.c).

And you comment the header importing importedCFile.c and the call to anExampled() function it would work fine.


Solution

  • Your problem is that the C code in importedFile.c is trying to call back C++ functions in mainCode.cu.

    In order to be callable from C, C++ functions must have C linkage. Declare getVector() as

    extern "C" int *getVector(int n)  {
    

    in mainCode.cu, and your example will compile fine.