在C++中extern
关键字用于声明一个变量或函数,这个变量或函数在其他文件中定义,这通常用于在多个源文件之间共享变量或函数。
对于任何在其他源文件中定义非静态变量或非静态函数,只要使用extern
关键字对其进行声明,即可在当前源文件下进行使用。
例如:
file1.cpp
int val = 1024;
file2.cpp
#include <iostream>
using namespace std;
extern int val;
int main () {
cout << val << endl;
}
上面程序file2.cpp
会打印出file1.cpp
中val
变量的值。
编译:
g++ file1.cpp file2.cpp -o excutable_file
因为源文件file2.cpp
使用到了file1.cpp
的变量,所以需要对两个源文件进行编译链接。
输出:
1024
当然extern
也可以声明函数,示例如下:
file3.cpp
#include <iostream>
using namespace std;
void myfunc() {
cout << "This is function from file3.cpp." << endl;
}
file4.cpp
extern void myfunc();
int main () {
myfunc();
}
编译:
g++ file3.cpp file3.cpp -o excutable_file2
输出:
This is function from file3.cpp.
需要注意的是:
extern
关键字只是声明了一个已经存在的变量或者函数,而不会创建新的存储空间。实际的存储空间是在变量的定义处或者函数的定义处创建的。并且extern
关键字是无法发现static
修饰的变量和函数的。