have to rename c code as .cpp before able to link

Say I just have a very simple “main.c” file which only calls another function like “hello();” and that hello function is defined in a cu file; hello.cu.

#include hello.h
int main(){

If i compile main.c with gcc, hello.cu with with nvcc, and link both with gcc, I get a “undefined reference to hello” error.

here’s the weird part though, if I name main.c as “main.cpp”, and compile main.cpp with gcc, gcc will finally link the files without complaint and the program works in the end.

Could someone please explain why this is happening, and anyway to fix it?



nvcc defaults to C++ for compiling host code. C++ does function name mangling, C doesn’t. If you are really using C++ features in the host code of the .cu file declared the function as

extern "C" myfunction() {}

and name mangling won’t happen, and argument handling will use strict C semnatics. If you host code is plain C, pass nvcc the argument --host-compilation C and it will use C compile the host code.