持续性
动态存储持续性
在函数和代码块中定义的变量,随着函数的开始进行存储,结束自动释放
只在函数和代码块内部具有生命期
静态存储持续性
在函数外或static关键字声明的变量在程序整个运行周期都存在
链接性
外部链接性
在函数外部定义的变量和普通函数都具有外部链接性,除了在本文件中可使用,在其他文件中也可以使用
内部链接性
函数外的static静态变量和static静态函数都具有内部链接性,在整个文件中都可以使用这些变量和函数,但在其他文件中不能使用,也即不具有外部链接性
无链接性
在函数或代码块内部的变量都没有链接性,之内在函数或代码块内部使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <iostream> using namespace std;
int n;
static int m;
void func() { int a; static int b; }
static void func_2() {
}
int main() { ... return 0; }
|
定义与声明
具有外部链接性的变量和函数,可以其他文件中声明,但不能定义([单定义规则](C++杂记 # 单定义规则)),对于变量的声明使用[[extern关键字]]
具有内部链接性的变量和函数,可以在其他文件中再次声明和定义,且两个变量和函数属于不同值,只在所在的文件中可访问
示例
static静态变量和全局变量的区别
静态和非静态的全局变量都能在整个文件中使用,但在其他文件中,非静态全局变量可以被使用,而静态全局变量不能使用
1 2 3 4 5 6 7 8 9 10
| #incluce <iostream> using namespace std;
int n=10; static int m=20;
int main() {
}
|
static静态函数和普通函数的区别
- 普通函数默认为全局函数,具有外部链接性,可在文件中共享,不能在两个文件中定义同一个函数,可以再次声明来使用同一函数
- static静态函数只在本文件中可用,具有内部链接性,可以在其他文件中定义同一函数
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <iostream> using namespace std; static int average(int a,int b) { return (a+b)/2; } void call(); int main() { cout<<average(3,6)<<endl; call(); return 0; }
|
other.cpp
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> using namespace std; double average(int a,int b) { return (a+b)/2.0; } void call() { cout<<average(3,6)<<endl; }
|