C++ functions can be used in C only if they have a type that can also be represented in C.
Depending on whether or not the C++ source is available, there are different ways to achieve linkage between functions.
If the C++ source code is available, the C++ function can be declared there with anextern “C”
directive; however, it must be declared with extern “C”
in every C++
source fragment that calls the function!
In the calling C source code, a “plain” extern
declaration is required for the C++ function.
If the C++ source is not available or a general new declaration and recompilation is too cumbersome, an additional function level can be inserted. This is done by writing a so-called “wrapper” function in C++ and defining it as extern “C”
. The wrapper function can then be called in C without restrictions.
Example
C++ function to be called:
int hidden(int i) { // ... }
Wrapper function:
extern int hidden(int); extern "C" int wrapper(int i) { return hidden(i); }
C source fragment that calls the wrapper function:
extern int wrapper(int); int main(void) { printf("%d\n", wrapper(100)); return 0; }
This technique can also be used if a C++ function contains a parameter with a type that does not directly match a C type. In the case of a C++ function with a reference type parameter, for example, a wrapper function with a parameter of type pointer could be written and called instead.