You need to use extern "C" in C++ when declaring a function that was implemented/compiled in C. The use of extern "C" tells the compiler/linker to use the C naming and calling conventions, instead of the C++ name mangling and C++ calling conventions that would be used otherwise. For functions provided by other libraries, you will almost never need to use extern "C", as well-written libraries will already have this in there for the public APIs that it exports to both C and C++. If, however, you write a library that you want to make available both in C and in C++, then you will have to conditionally put that in your headers.
1. If you have a function implemented in C and want to call it from C++.
1.1). if you can modify C header files
Typically the declarations in a C header file are surrounded with
#ifdef __cplusplus
extern "C" {
#endif
[... C declarations ...]
#ifdef __cplusplus
}
#endif
to make it usable from C++.
1.2). if you cannot modify C header files
include the header files in C++ source files
extern "C" {
/* include c library header */
}
or wrap the necessary c headers in a seperate header file then include it
#ifdef __cplusplus
extern "C" {
#endif
/* include c library header */
#ifdef __cplusplus
} // extern
#endif
1.3). If you only want to call several C functions, and for some reason you don't have or don't want to #include a C header file in which that function is declared, you can declare the individual C function in your C++ code using the extern "C"
syntax.
extern "C" {
[... function declarations...]
}
After this you simply call the function just as if it were a C++ function
2. If you have a function implemented in C++ and want to call it from C.
// This is C++ code
// Declare using extern "C":
extern "C" void cplusplus_func_name(paramlist);
...
// Define function in some C++ module:
void cplusplus_func_name(paramlist)
{
...
}
The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn't supported by C, you can't make several overloaded functions simultaneously callable by a C program.
评论