C 中全局和局部范围内的静态变量
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
段.
我有以下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
段.