C++中static内部链接和extern外部链接

我们在进行多文件编译时,会遇到在不同文件中存在同名变量的问题,但是相同变量存在两种情况:
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.cppmain函数通过调用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
发布了337 篇原创文章 · 获赞 43 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/dghcs18/article/details/104185604