我们在进行多文件编译时,会遇到在不同文件中存在同名变量的问题,但是相同变量存在两种情况:
1、两个文件中的同名变量实际上是相同的变量
2、两个文件中的同名变量实际上是不同的变量
对于第一种情况,实际上相同的意思是两个变量的地址也一样,就是相同的变量,但是声明在不同的文件中而已。对于这种情况,我们C++引入了extern
关键字
extern
//file1.cpp
#include<iostream>
using namespace std;
int count = 10;
void printing();
int main()
{
count++;
printing();
}
file1.cpp
中定义了一个全局变量count
,并且在main
函数中进行自增运算。
//file2.cpp
#include<iostream>
using namespace std;
extern int count;
void printing()
{
cout << count;
}
file2.cpp
中声明了一个外部链接extern
同名变量,是的可以在file2.cpp
中使用该变量,实际上这两个变量是同一个变量。
编译两个文件,输出count
自增之后的数值!
PS D:\程序\随笔程序\2020年1月> g++ file1.cpp file2.cpp -o main
PS D:\程序\随笔程序\2020年1月> ./main
11
static
在文首的第二种情况中,两个文件中的变量只是同名,但是实际上是不同的变量,也存储在不同的地址。
//file1.cpp
#include<iostream>
using namespace std;
int count = 4;
void printing();
int main()
{
count++;
cout << "count in file1:" << count << endl;
printing();
}
file1.cpp
中声明了一个全局的int
变量,自增后输出
//file2.cpp
#include<iostream>
using namespace std;
static int count = 9;
void printing()
{
cout << "count in file2:" << count << endl;
}
file2.cpp
中也定义了一个同名变量,并且是使用static
关键字进行内部链接,因此,两个变量实则不同。
file1.cpp
的main
函数通过调用file2.cpp
中实现的函数,来输出file2.cpp
中的count
变量。
PS D:\程序\随笔程序\2020年1月> g++ file1.cpp file2.cpp -o main
PS D:\程序\随笔程序\2020年1月> ./main
count in file1:5
count in file2:9