extern 主要有两方面作用:
分离编译
extern 表示一个外部变量:
- 外部变量必须定义在所有函数之外。
- 在一个源程序的所有文件中,一个外部变量只能在某文件中定义一次,而其他文件可以通过extern声明来访问它(定义外部变量的源文件中也可以包含对该外部变量的extern声明)。
- 外部变量的定义中必须指定数组的长度,但extern声明则不一定要指定数组的长度。
- 外部变量的初始化只能出现在其定义中。
// file1
extern int sp;
// file2
int sp = 0;
对于const 类型的外部变量,其声明和定义都需要加上extern关键字,即 extern const
链接指令
extern “C” 是链接指令(Linkage Directives),让 C++ 编译器将 extern “C” 声明的代码当作 C 语言代码处理,用于支持非C++语言的代码。
// declaring a Non-c++ function
// single statement
extern "C" size_t strlen(const char *);
// compound statement
extern "C" {
int strcmp(const char*, const char*);
char *strcat(char*, const char*);
}
// 用于头文件
extern "C" {
#include <string.h>
}