[英]Static variables in global and local scope in C
我有以下 C 程序
#include <stdio.h>
static int aa = 10;
void func(){
static int aa = 9;
printf("%d\n",aa);
}
int main()
{
func();
return 0;
}
输出为 9。
当使用 nm 命令查看输出时,我得到了这个
0000000000601038 d aa
000000000060103c d aa.2286
0000000000601040 B __bss_start
0000000000601040 b completed.7585
0000000000601028 D __data_start
0000000000601028 W data_start
0000000000400460 t deregister_tm_clones
00000000004004e0 t __do_global_dtors_aux
0000000000600e18 t __do_global_dtors_aux_fini_array_entry
0000000000601030 D __dso_handle
0000000000600e28 d _DYNAMIC
0000000000601040 D _edata
0000000000601048 B _end
00000000004005d4 T _fini
前两行表示两个变量都在数据段中,但第二行中的 2286 是什么。 它说明什么?
它表示func
范围内的局部静态变量aa
,该变量仅被系统的动态加载器初始化一次。 从翻译单元外部看不到它,但它也在data
段中,因为这是开始时快速初始化的地方。
索引2286是随机生成的,这样如果你在不同的局部范围内静态声明了很多名为aa
变量,就可以相互区分,同时将所有变量都保存在data
段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.