外部链接性意味着文件间可以共享,内部链接性意味着只能在文件内部共享,无链接性就是局部变量,不可共享。
例如使用具有外部链接性的全局变量。创建 test.cpp,内容为:
int global = 1000;
另创建 main.cpp,其内容如下。最终可以输出 global 为 1000。
#include<iostream>
using namespace std;
extern int global; // 注意引入具有外部链接性的全局变量需要添加 extern 的声明
int main()
{
cout << global << endl; // 1000
return 0;
}
内部链接性的例子就是文件内部的使用 static 修饰的全局变量,其无法被文件外部访问。
另外需要注意的是,使用 const 修饰的不加 static 的全局变量,其具有内部链接性。如果让其具有外部链接性,还需要添加 extern 关键字。创建 test.cpp,内容为:
// const int global = 1000; // 具有内部链接性
extern const int global_const = 2000; // 具有外部链接性
另创建 main.cpp,其内容如下。最终结果输出为 2000。
#include<iostream>
using namespace std;
// extern int global; // 注意引入具有外部链接性的全局变量需要添加 extern 的声明
extern const int global_const;
int main()
{
cout << global_const << endl; // 2000
return 0;
}