Calling C Functions from C++
To prevent the C++ compiler from mangling the name of a C function, you can apply the extern "C" linkage specifier to the declaration or declarations, as shown in the following example:
//C++ code
//One C function
extern "C" void f(int);
//More than one C funtions
extern "C" {
int f1(int);
int f2(double);
int f3(int);
};
int main()
{
f(3);
int i = f1(4);
// ...
}
If you know a library file is compiled by a C compiler, and you want to call the functions contained in this library from C++ codes, you have to include the corresponding head file using this mechanism.
//C++ code
extern "C"
{
#include "cinclude.h"
}
int main()
{
f(3);// void f(int) is declared in cinclude.h
...
}
If you are able to change the C header, you should strongly consider adding the extern "C" {...} logic inside the header to make it easier for C++ users to #include it into their C++ code.
/* cinclude.h */
#ifdef __cplusplus
extern "C" {
#endif
/* C-functions */
int f(int);
#ifdef __cplusplus
}
#endif
Why is extern “C“ surrounded with #ifdef and #endif? this is because a C compiler won't understand the extern "C" construct, you have to wrap the extern "C" { and } lines in an #ifdef so they won't be seen by normal C compilers. The standard C library header files, such as stdio.h, are built in this manner.
Now you can #include your C header without any extern "C" linkage specifier in your C++ code:
// C++ code
#include "cinclude.h"
int main()
{
f(3); // Note: nothing unusual in the call
...
}