Call a C function from C++ code

Dangila picture Dangila · May 31, 2013 · Viewed 108.6k times · Source

I have a C function that I would like to call from C++. I couldn't use "extern "C" void foo()" kind of approach because the C function failed to be compiled using g++. But it compiles fine using gcc. Any ideas how to call the function from C++?

Answer

Prof. Falken picture Prof. Falken · May 31, 2013

Compile the C code like this:

gcc -c -o somecode.o somecode.c

Then the C++ code like this:

g++ -c -o othercode.o othercode.cpp

Then link them together, with the C++ linker:

g++ -o yourprogram somecode.o othercode.o

You also have to tell the C++ compiler a C header is coming when you include the declaration for the C function. So othercode.cpp begins with:

extern "C" {
#include "somecode.h"
}

somecode.h should contain something like:

 #ifndef SOMECODE_H_
 #define SOMECODE_H_

 void foo();

 #endif


(I used gcc in this example, but the principle is the same for any compiler. Build separately as C and C++, respectively, then link it together.)