C++中的全局变量,分为静态、有外部链接性的变量和静态、内部链接性的变量。
1. 静态、外部链接性变量
在file1中如下定义:
#include "iostream"
using namespace std;
void printGlobalinFile2();
void printGlobalinFile3();
void printnotGlobalinFile3();
void printnotGlobalinFile4();
int global = 0; //全局、外链性变量
int main()
{
cout<<global<<" in file1"<<endl;
printGlobalinFile2();
printGlobalinFile3();
printnotGlobalinFile3();
printnotGlobalinFile4();
}
在file2中定义如下:
#include "iostream"
using namespace std;
extern int global; //引用file1中的global变量
//int global = 1; //错误
void printGlobalinFile2()
{
cout<<global<<" in file2"<<endl;
}
2. 静态,内部链接性
在file3中定义如下:
#include "iostream"
using namespace std;
static int global = 1; //加上static关键字后,覆盖file1中的global
static int notGlobal = 2; //内部链接性
void printGlobalinFile3()
{
cout<<global<<" in file3"<<endl;
}
void printnotGlobalinFile3()
{
cout<<notGlobal<<" in file3"<<endl;
}
在file4中定义如下:
#include "iostream"
using namespace std;
extern int notGlobal; //错误
static int notGlobal = 3; //ok
void printnotGlobalinFile4()
{
cout<<notGlobal<<" in file4"<<endl;
}
输出结果为:
0 in file1
0 in file2
1 in file3
2 in file3
3 in file4
PS : 对于未被初始化的外链性的变量,系统默认会为其赋值为0;