1. The concept of extern “C”
extern "C" is a syntax feature provided by C++ for calling and using C language-style functions and variables in C++ code. C++ and C have some different compilation and linking conventions at the bottom level, which will cause the compiled function name of C++ to carry extra information when linking, which does not match the function name of the C code. By using extern "C", we can tell the compiler to process function names and links according to the conventions of the C language, thereby achieving mixed programming of C and C++.
2. Use of extern “C”
① Calling C language functions in C++
Normally, the function name in C++ will be modified by some names to include information such as parameter types. But if we want to call a function written in C language in C++, we need to ensure that the function name and linkage method are compatible with C language.
extern "C" {
void cFunction(int a, int b); // 在 C++ 代码中声明 C 语言风格的函数
}
int main() {
cFunction(5, 3); // 调用 C 语言风格的函数
return 0;
}
②Use C language variables in C++
Similarly, if we want to use C language global variables in C++, we also need to use extern "C".
extern "C" {
int cGlobalVariable; // 在 C++ 代码中声明 C 语言风格的全局变量
}
int main() {
cGlobalVariable = 10; // 使用 C 语言风格的全局变量
return 0;
}
③Including C language header files in C++
If you include a C language style header file in C++ code, you need to use extern "C" to ensure correct linking.
extern "C" {
#include "c_header.h" // 包含 C 语言风格的头文件
}
int main() {
cFunction(5, 3); // 调用 C 语言风格的函数
return 0;
}