CodeKingPlusPlus CodeKingPlusPlus - 5 months ago 63
C Question

C and C++ linkage with extern "C"

I have a C++ function defined in a .h file as follows and implemented in a .cpp file:

extern "C" void func(bool first, float min, float* state[6], float* err[6][6])
//uses vectors and classes and other C++ constructs

How can I call func in a C file? How do I set up my file architecture / makefile to compile this?



To call it in C, all you need to do is call it normally. Because you told the compiler to use the C calling conventions and ABI with extern "C", you can call it normally:


To compiler, use this for the C++:

g++ -c -o myfunc.o myfunc.cpp

Then this for the C:

gcc -c -o main.o somec.c

Than link:

g++ -o main main.o myfunc.o

Make sure that the C++ header for the function uses ONLY C CONSTRUCTS. So include things like <vector> in the .cpp file instead.