【问题标题】:In which memory segment a program global and local static variables are saved程序全局和局部静态变量保存在哪个内存段
【发布时间】:2013-10-04 19:15:25
【问题描述】:

据我所知,全局静态变量存储在 .Data 和 .Bss 段中。

(global) static int i; ---> .BSS
(global) static int i=10; ---> .Data

如果是这种情况,具有相同全局静态变量的多个文件如何从整个程序共有的内存位置访问变量。

例如。

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?

我的第二个问题是,函数内部定义的局部静态变量存储在程序内存的哪一段?

【问题讨论】:

    标签: c unix memory memory-management


    【解决方案1】:

    问题第二部分的简化解释:-

    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
    

    【讨论】:

      【解决方案2】:

      涉及各种“命名空间”,您应该想象每个对象文件都包含其自己的“命名空间”,用于其静态变量。

      请记住,名称不存储在.bss(或.data)段内。

      为了简化图片,想象当编译成 foo.o 时,foo.c 内部的 static int i; 的“汇编程序”名称类似于 $foo.o$i

      情况并非完全如此,但您明白了……实际上,您可以理解static 的变量名称​​不 生成到目标文件中。该静态变量仍然(粗略地说)在.bss 或.data 中,但它的名称不可见。

      使用GNU objdump 探索对象ELF 可重定位文件。

      【讨论】:

      • 感谢您的回答,它澄清了我的第一个疑问。局部静态变量呢?
      • static 在某个函数内部声明的变量是static 数据,只是它们的名称在函数外部无法访问(所以粗略地说它们的程序集名称就好像它是随机生成的)。
      • 感谢 Basile Starynkevitch :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2015-10-04
      • 2012-08-12
      • 2015-09-02
      相关资源
      最近更新 更多