C++中extern "C"的作用是什么?
在 C++ 中,extern "C" 的作用是告诉编译器按照 C 语言的规范来处理函数名和变量名。这是因为 C++ 编译器会对函数名和变量名进行名称修饰(name mangling),以区分不同的函数和变量。而在 C 语言中,函数名和变量名不会被名称修饰,因此需要使用 extern "C" 来告诉编译器使用 C 语言的规则。
下面是微软官方文档关于“extern "C"”的使用说明:
extern (C++) | Microsoft Learn

extern (C++) | Microsoft Learn

以下示例演示如何声明具有 C 链接的名称:
// Declare printf with C linkage.
extern "C" int printf(const char *fmt, ...);
// Cause everything in the specified
// header files to have C linkage.
extern "C" {
// add your #include statements here
#include <stdio.h>
}
// Declare the two functions ShowChar
// and GetChar with C linkage.
extern "C" {
char ShowChar(char ch);
char GetChar(void);
}
// Define the two functions
// ShowChar and GetChar with C linkage.
extern "C" char ShowChar(char ch) {
putchar(ch);
return ch;
}
extern "C" char GetChar(void) {
char ch;
ch = getchar();
return ch;
}
// Declare a global variable, errno, with C linkage.
extern "C" int errno;
首先看看
作为一种面向对象的语言,
void foo( int x, int y );
该函数被