Dangila Dangila - 6 months ago 12
Linux Question

Call a C function from C++ code

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

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.hshould 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.)