static 与 extern是用来做标识符作用域限定的。
程序1: test.cpp
#include <iostream>
using namespace std;
int MAX = 8 ;
void func1(){
cout << "func1 output " << endl ;
}
其中定义了两个标识符, MAX和func1,由于他们都没有static修饰,他们默认的修饰符就是extern。
extern 说明这两个标识符在其它文件中也可以使用。
这里的其它文件是指没有 #include "test.cpp" 的文件,如果include了,就是同一个文件了。
那其它文件怎么使用这两个标识符呢?
程序2 :
#include <iostream>
using namespace std;
extern int MAX ;
void func1() ;
int main()
{
cout <<"Hello world!" << endl;
cout << MAX << endl ;
func1() ;
return 0;
}
每一个要使用MAX而且没有包含"test.cpp"的文件,都需要用 extern int MAX 来声明这个变量,而函数的声明不需要extern修饰。
编译这两个文件 :
g++ main.cpp test.cpp
static 的作用是将标识符作用域限定在本文件内。
比如我们修改 test.cpp如下。
#include <iostream>
using namespace std;
static int MAX = 8 ;
void func1(){
cout << "func1 output " << endl ;
}
修改main.cpp如下:
#include <iostream>
using namespace std;
void func1() ;
static int MAX = 100 ;
int main()
{
cout <<"Hello world!" << endl;
cout << MAX << endl ;
func1() ;
return 0;
}
将他们两个编译 : g++ main.cpp test.cpp 。
如果把两个static都去掉,会报重复定义错误,去掉一个还可以。
简而言之:
extern的作用是不用include某个文件,也能通过extern声明使用这个文件中的全局变量。
static的作用是,如果两个文件不相互包含,而且分别都定义了相同名称的变量,为了让整体编译通过,要把它们其中一个定义为static。