C++静态存储持续性之内部链接性---静态全局变量

一、概念

static 限定符用于作用域为整个文件的变量时,该变量的链接性将为内部的。在多文件程序中,内部链接性和外部链接性之间的差别很有意义。链接性为内部的变量只能在其所属的文件中使用;但常规外部变 量都具有外部链接性,即可以在其他文件中使用。
思考:如果要在其他文件中使用相同的名称来表示其他变量,该如何办呢?
除了使用extern关键字,还可以 使用static修饰变量将变量作用域限制在文件中
二、示例代码
file1.cpp
#include <iostream>
int tom=3;
int harry=300;

void remote_access();
using namespace std;

int main()
{

    cout <<"main() reports the following addressses:\n";
    cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    cout <<"file1.cpp &harry"<<&harry<<",,,,harry="<<harry<<endl;

    remote_access();
 
    return 0;
}

file2.cpp

#include <iostream>
 extern int tom;

static int harry=200;

void remote_access()
{
    using namespace std;
    cout << "remote_access() reports the follwing addresses:\n";
    cout <<"file2.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    cout <<"file2.cpp &harry"<<&harry<<",,,,harry="<<harry<<endl;
  
}

编译上面两个cpp文件: g++ file1.cpp file2.cpp -o test

执行结果如下:

main() reports the following addressses:
file1.cpp &tom0x403010,,,,tom=3
file1.cpp &harry0x403014,,,,harry=300
remote_access() reports the follwing addresses:
file2.cpp &tom0x403010,,,,tom=3
file2.cpp &harry0x403020,,,,harry=200

总结:以上说明,使用extern达到只有一个变量效果,遵循变量单一规则,只定义一次,内存地址为同一个(file1.cpp中的tom变量内存地址和file2.cpp中的变量内存地址为同一个);使用static声明变量,相当于重新申请变量(file1.cpp中的harry变量内存地址和file2.cpp中的变量内存地址不是同一个),该变量作用域为file2.cpp中,即本文件中,也可以达到单一变量规则,原理类似使用namespace。

猜你喜欢

转载自blog.csdn.net/banzhuantuqiang/article/details/130912644