如何存储全局变量? [英] How are global variables stored?

查看:151
本文介绍了如何存储全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,有两种类型的全局变量,初始化 unintialized 。它们如何存储?它们都存储在可执行文件中吗?我可以认为初始化的全局变量的初始值存储在可执行文件中。

AFAIK, there're 2 types of global variables, initialized and unintialized. How are they stored? Are they both stored in the executable file? I can think of initialized global variables having their initial values stored in executable file. But what needs to be stored for the uninitialized ones?

我目前的理解是这样的:

My current understanding is like this:

可执行文件被组织为几个部分,例如.text,.data和.bss。代码存储在.text段中,初始化的全局或静态数据存储在.data段中,未初始化的全局或静态数据存储在.bss段中。

Executable file is organized as several sections, such as .text, .data, and .bss. Code is stored in .text section, initialized global or static data is stored in .data section, and uninitialized global or static data is stored in .bss section.

您可以查看我的问题。

我在此找到了很好的参考:

I found a good reference here:

汇编语言源中的段 -
使用.text,.data和.bss指令构建文本和数据段

@Michael


  1. 我在我的汇编代码中定义了一个100字节的未初始化数据区,这100个字节不存储在可执行文件中,因为它未初始化。

  1. I define a 100 bytes of un-initialized data area in my assembly code, this 100-bytes is not stored in my executable file because it is NOT initialized.

谁将在RAM中分配100字节未初始化的内存空间?

Who will allocate the 100-byte uninitialized memory space in RAM? The program loader?

假设我有以下代码:

int global[100];

void main(void)
{
   //...
}

全局[100]未初始化。如何将全局[100]重新编码在我的可执行文件?谁将在什么时间分配它?如果它被初始化了怎么办?

The global[100] is not initialzed. How will the global[100] be recoded in my executable file? And who will allocate it at what time? What if it is initialized?

推荐答案

初始化的变量值存储在 .data 段的可执行文件。未初始化的不必存储。它们最终在RAM中的 .bss 段中,但是在可执行文件中段的大小为零,只是所需的内存量存储在段描述符中。 .text 部分中的代码通过偏移量访问这些到段中。 运行时链接器加载器将这些引用修补为实际的虚拟地址。请参见例如可执行文件和可链接格式,该文件用于大多数类Unix操作系统。

Initialized variable values are stored in the .data segment of the executable. Uninitialized ones don't have to be stored. They end up in the .bss segment in RAM, but the size of the segment is zero in the executable file, just the required amount of memory is stored in the segment descriptor. The code in the .text section is accessing these via offsets into the segment. Runtime linker-loader patches these references to actual virtual addresses. See, for example, the Executable and Linkable Format, which is used on most Unix-like operating systems.

这篇关于如何存储全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆