C++中如何处理链接性为外部和内部的变量

C++中如何处理链接性为外部和内部的变量

可使用外部变量在多文件程序的不同部分之间共享数据;可使用链接性为内部的静态变量在同一个文件中的多个函数之间共享数据(名称空间提供了另外一种共享数据的方法)。另外,如果将作用域为整个文件的变量变为静态的,就不必担心其名称与其他文件中的作用域为整个文件的变量发生冲突。
程序清单97和程序清单98演示了C++如何处理链接性为外部和内部的变量。程序清单9.7(twofile1.cpp)定义了外部变量 tom 和 dick 以及静态外部变量 harry。这个文件中的 main()函数显示这3个变量的地址,然后调用remote_access()函数,该函数是在另一个文件中定义的。程序清单9.8(twofile2.cpp)列出了该文件。除定义remote_access()外,该文件还使用 extem 关键字来与第一个文件共享 tom。接下来,该文件定义一个名为 dick 的静态变量。static 限定符使该变量被限制在这个文件内,并覆盖相应的全局定义。然后,该文件定义了一个名为 harry 的外部变量,这不会与第一个文件中的 harry 发生冲突,因为后者的链接性为内部的。参见【0voice C++】随后,remote-access()函数显示这3个变量的地址,以便于将它们与第一个文件中相应变量的地址进行比较。别忘了编译这两个文件,并将它们链接起来,以得到完整的程序。

// twofile1.cpp -- variables with external and internal linkage
#include <iostream>     // to be compiled with two file2.cpp
int tom = 3;            // external variable definition
int dick = 30;          // external variable definition
static int harry = 300; // static, internal linkage
// function prototype
void remote_access();

int main()
{
    using namespace std;
    cout << "main() reports the following addresses:\n";
    cout << &tom << " = &tom, " << &dick << " = &dick, ";
    cout << &harry << " = &harry\n";
    remote_access();
    // cin.get();
    return 0; 
}
// twofile2.cpp -- variables with internal and external linkage
#include <iostream>
extern int tom;         // tom defined elsewhere
static int dick = 10;   // overrides external dick
int harry = 200;        // external variable definition,
                        // no conflict with twofile1 harry

void remote_access()
{
    using namespace std;
		
    cout << "remote_access() reports the following addresses:\n";
    cout << &tom << " = &tom, " << &dick << " = &dick, ";
    cout << &harry << " = &harry\n";
}

下面是编译程序清单9.7和程序清单9.8生成的程序的输出:

main()reports the following addresses :
0x0041a020=&tom,0x0041a024=&dick,0x0041a028=&harry
remote access()reports the following addresses:
0x0041a020=&tom,0x0041a450=&dick,0x0041a454=&harry

从上述地址可知,这两个文件使用了同一个tom 变量,但使用了不同的 dick 和 harry 变量。具体的地址和格式可能随系统而异,但两个tom 变量的地址将相同,而两个 dick 和 harry 变量的地址不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值