据我所知,全局静态变量存储在.Data和.Bss段中。
(global) static int i; ---> .BSS
(global) static int i=10; ---> .Data
如果是这种情况,那么具有相同全局staic变量的多个文件如何从整个程序通用的内存位置访问变量。
实施例。
test.c
static int i=10;
void fun(){
printf("%d", i );
}
test1.c
static int i=20;
void fun1(){
printf("%d", i);
}
test.c和test1.c如何从.Data段解析i?
我的第二个问题是在函数内定义的程序存储器局部静态变量的哪一段存储?
答案 0 :(得分:2)
涉及各种“名称空间”,您应该想象每个目标文件的静态变量都包含自己的“名称空间”。
请注意,这些名称不会存储在.bss
(或.data
)细分中。
大致简化图片想象一下,当编译成foo.o
时,static int i;
内foo.c
的“汇编程序”名称会像$foo.o$i
情况并非如此,但您明白了......实际上,您可以理解,对于static
变量,名称不是生成到目标文件中。该静态变量仍然(严重地说)在.bss
或.data
中,但其名称不可见。
使用GNU objdump探索对象ELF可重定位文件。
答案 1 :(得分:0)
问题第二部分的简化说明: -
1.Auto variables are stored in stack segment.
2.Uninitialized global variables are stored in BSS segment.
3.Initialized global variables and global static variables are stored in data segment.
***4.Local static variables are stored in data segment of the memory.***
Scope:- Only the function in which it is declared
Lifetime:- From when control enters the function in which it is declared till when control exits the function
Scope:- Global variables can be accessed from anywhere in the program
Lifetime:- Entire life of program execution
Scope:- Global static variables can be accessed from anywhere inside the file in which they are declared
Lifetime:- Entire life of program execution
Scope:- Local static variables can be accessed inside the function where it is declared
Lifetime:- Entire life of program execution