C and C ++ with external "C"

I have a C ++ function defined in the .h file as follows and implemented in the .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 to configure my file architecture / make file to compile this?

Thanks!

+4
source share
4 answers

To call it in C, all you have to do is call it normally. Since you told the compiler to use the C-call and ABI conventions with extern "C" , you can call this usually:

 func(args); 

For the compiler, use this for C ++:

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

Then this is for C:

 gcc -c -o main.o somec.c 

Than the 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 your .cpp file.

+4
source

You call a function from C in the usual way. However, you need to wrap extern "C" in a preprocessor macro to prevent its C compiler:

 #ifndef __cplusplus extern "C" #endif void func(bool first, float min, float* state[6], float* err[6][6]); 

Assuming you are working with GCC, then compile the C code with gcc , compile the C ++ code with g++ , and then link it to g++ .

+9
source

call it in C using

 func(... // put arguments here); 

Saying extern "C", you ask the compiler not to interfere with your names. Otherwise, the C ++ compiler will be prone to customize them (i.e. add additional characters to make them unique) before the linker.

You will also want to make sure that you have the setting to use the C-calling convention.

+3
source
 //header file included from both C and C++ files #ifndef __cplusplus #include <stdbool.h> // for C99 type bool #endif #ifdef __cplusplus extern "C" { #endif void func(bool first, float min, float* state[6], float* err[6][6]); #ifdef __cplusplus } // extern "C" #endif 

 // cpp file #include "the_above_header.h" #include <vector> extern "C" void func(bool first, float min, float* state[6], float* err[6][6]); { //uses vectors and classes and other C++ constructs } // c file #include "the_above_header.h" int main() { bool b; float f; float *s[6]; float *err[6][6]; func(b,f,s,err); } 
+1
source

All Articles