C and C++ linkage with extern “C”

2019-05-07 10:53发布

问题:

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?

Thanks!

回答1:

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:

func(args);

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.



回答2:

You call the function from C in the normal way. However, you need to wrap the extern "C" in an preprocessor macro to prevent the C compiler from seeing it:

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

Assuming you're working with GCC, then compile the C code with gcc, compile the C++ code with g++, and then link with g++.



回答3:

call it in C using

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

By saying extern "C" you are asking the compiler not to mangle your names. Otherwise, C++ compiler would tend to mangle them (i.e. add additional symbols to make them unique) before the linker.

You'll also want to make sure you have setup to use C calling convention.



回答4:

//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);
}