In C++, extern "C"
it is a linkage specification , which tells the C++ compiler to process the declared function or variable in the linkage manner of C language. This declaration is mainly used when referencing libraries written in C language in C++ code.
The C++ compiler will adapt the function name (Name Mangling) during the compilation process , also known as name mangling , to support features such as function overloading . The so-called adaptation is to attach some additional information to the function name, such as parameter type and quantity, so that the correct function can be found when linking . Therefore, the form of the same function name compiled in C++ may be different from that compiled in C.
However, the C language does not support function overloading, so in the C language, the function name will not be adapted after compilation, and remains the original function name. Therefore, if you directly refer to a C function in C++, the linker may not be able to find the correct function due to name mangling.
extern "C"
It was created to solve this problem. It tells the C++ compiler that the declared function or variable is written in C and should be linked as C, that is, without name mangling.
For example, if you have a C library file "c_library.h", you can reference it in C++ like this:
extern "C" {
#include "c_library.h"
}
In this way, c_library.h
all functions and global variables in will be linked in C language, and can be correctly referenced in C++ code.
Note that extern "C"
it can be used not only to include entire header files, but also to single function or variable declarations, for example:
extern "C" void c_function(); // 声明一个C语言的函数
extern "C" int c_variable; // 声明一个C语言的全局变量
Additionally, extern "C"
it can be used with curly braces {} to include multiple C functions or variables:
extern "C" {
void c_function1();
void c_function2();
int c_variable;
}
In this way, c_function1
, c_function2
and c_variable
will be linked in the C language.