I want to know why we cant access variables those declared inside functions from outside the function? Its technically possible to access them since they put in .data segment just like global/static variables. Also what is the difference between a global variable and static global variable?
I have a C
file as following:
int global_n =1;
static int global_static_n=2;
int main(){
int local_n=3;
static int local_static_n=4;
return 0;
}
void test(){
global_n=9;
global_static_n=8;
//local_n=7;
//local_static_n=6;
}
I compile and link it by the following GCC
command:
gcc -Wall -m32 -nostdlib main.c -o main.o
I disassemble it by the following OBJDUMP commands:
objdump -w -j .text -D -Mi386,addr32,data32,intel main.o
objdump -w -s -j .data main.o
And get the following dump:
Disassembly of section .text:
080480f8 <main>:
80480f8: 55 push ebp
80480f9: 89 e5 mov ebp,esp
80480fb: 83 ec 10 sub esp,0x10
80480fe: c7 45 fc 03 00 00 00 mov DWORD PTR [ebp-0x4],0x3
8048105: b8 00 00 00 00 mov eax,0x0
804810a: c9 leave
804810b: c3 ret
0804810c <test>:
804810c: 55 push ebp
804810d: 89 e5 mov ebp,esp
804810f: c7 05 00 a0 04 08 09 00 00 00 mov DWORD PTR ds:0x804a000,0x9
8048119: c7 05 04 a0 04 08 08 00 00 00 mov DWORD PTR ds:0x804a004,0x8
8048123: 90 nop
8048124: 5d pop ebp
8048125: c3
Contents of section .data:
804a000 01000000 02000000 04000000
I can see that local_static_n
put in .data segment just like global_static_n
and global_n
. If i uncomment following lines i will get the errors:
local_n=7;
local_static_n=6;
error: ‘local_n’ undeclared (first use in this function)
error: ‘local_static_n’ undeclared (first use in this function)
If static
is used in a namespace scope (i.e. outside of functions and classes), then the respective variable is visible for this translation unit only, and not for other translation units. This construct is used for avoiding unintentional name clashes of global variables defined in different translation units / libraries. This is known as "internal linkage"
If static
is used for a variable in a function, this variable has static storage duration, but it is visible only inside the function, not outside.
Note that this "visibility" just limits the compiler when accessing the variable through its name. Of course, a function may return or otherwise expose the address of static
variables in other ways; yet the variable itself is not visible to the compiler outside of above mentioned scopes.