parera riddle
parera riddle

Reputation: 148

Static variables in global and local scope in C

I have the following C program

 #include <stdio.h> 

 static int aa = 10;          

 void func(){
    static int aa = 9;
    printf("%d\n",aa);

}
int main()
{ 
    func();
    return 0;
}

The output is 9.

When used the nm command to see the output, I got this

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

In the first two rows says both the variables are in the data segment, but whats that 2286 in the second row. What does it indicate?

Upvotes: 2

Views: 325

Answers (1)

alinsoar
alinsoar

Reputation: 15783

It indicates the local static variable aa from the scope of func, this variable is initialized only once by the dynamic loader of the system. It is not seen from outside of the translation unit, but it is also in data segment, as this is where the initialization is made fast at the beginning.

The index 2286 is randomly generated, such that if you declare many variables named aa statically in different local scopes, to be able to distinguish each other and in the same time to keep all in data segment.

Upvotes: 2

Related Questions