C++ integration: 'undefined reference to main'


Apologies if this has been posted elsewhere, I couldn’t find anything using search.

I am trying to integrate working CUDA code into a working C++ program, but am faced with a compile error I can’t seem to work out.

Without posting all the code, here’s how I have it set up. It’s based on the ‘C++ Integration’ sample code from here.

== main.h ==

// includes

int main(int argc, char **argv);

extern "C" void gpuDivide(float* image, unsigned int width, unsigned int height, float divisor);

== main.cpp ==

#include "main.h"

int main(int argc, char **argv)


	// code


== GpuIntegration.cu ==

#include "GpuKernel.cu"

extern "C" void gpuDivide(float* image, unsigned int width, unsigned int height, float divisor)


	divide<<< 1,1 >>>(image, width, height, divisor);


== GpuKernel.cu ==

__global__ void divide(float *image, unsigned int width, unsigned int height, float divisor)


	// code


Compile command:

/usr/local/cuda/bin/nvcc -I/usr/local/cuda/include -O2 -g -c

The compiler comes up with the following:

make all 

Building file: ../GpuIntegration.cu

Invoking: C Compiler

/usr/local/cuda/bin/nvcc -o "GpuIntegration.o" "../GpuIntegration.cu"

/usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib/crt1.o: In function `_start':

/build/buildd/eglibc-2.10.1/csu/../sysdeps/x86_64/elf/start.S:109: undefined reference to `main'

collect2: ld returned 1 exit status

make: *** [GpuIntegration.o] Error 1

I’ve been struggling with this since last week, which has stifled my progress. Any suggestions on how to fix this are most welcome!

Thanks for your help,


Probably function name mangling inside main.cpp . It is a bit hard to tell, but it looks like you are linking with gcc. If the C++ compiler has mangled main() into something else in the output object file, the plain C linker won’t know what to do. It should be trivial to confirm this using objdump (presuming this is linux/elf, if it is OS X then there is a mach tool which does the same thing but I can’t remember what it is called off the top of my head) to look at the symbols in the output.

The remedy is either to link with g++, as opposed to gcc, or declare main as extern “C” as well, which should defeat the symbol name mangling and make it work as expected.

The solution turned out to be much simpler (more stupid) than I suspected.

Am using Eclipse as an IDE. In the compiler command line settings, I removed the ${flags} parameter as it was adding -MMD as an option which nvcc didn’t like. However, having removed the flags, I forgot to put the -c option back. The compiler was trying to link straight after compiling the first source file, and it couldn’t find a main function.

D’oh! Thanks for your help avidday.