To Call a C++ function from C , you need to use extern “C” with the C++ function and call it from your C/C++ code. The extern "C"
line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling. Below is the implementation:
// C++ code:
extern "C" void fun(char);
void fun(char x)
{
// ...
}
fun() can be used like this below
/* C code: */
void fun(char);
void cCode(char x)
{
fun(x);
/*
.
.
. */
}
This works only for non-member functions. If you want to call member functions (including virtual functions) from C, you need to provide a simple wrapper. See the below implementation:
// C++ code:
class CCall {
// declare something
virtual int fun(char);
};
extern "C" int call_C_fun(CCall* p, char x) // wrapper function
{
return p->fun(x);
}
Now fun() can be used like below:
/* C code: */
double call_C_fun(struct CCall* p, char x);
void ccCall(struct CCall* p, char x)
{
double d = call_C_fun(p,x);
/* ... */
}
If you want that you have to call overloaded functions from your C program, you must provide wrappers with different names for the C code to use. For example:
// C++ code:
void fun(char);
void fun(int);
extern "C" void fun_c(char x) { fun(x); }
extern "C" void fun_i(int i) { fun(i); }
Now the fun() can be used like this:
/* C code: */
void fun_i(int);
void fun_c(char);
void ccccode(int i,char x)
{
fun_i(i);
fun_c(c);
/* ... */
}