为什么需要 .bss 段? [英] Why is the .bss segment required?

查看:45
本文介绍了为什么需要 .bss 段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所知道的是全局变量和静态变量存储在 .data 段中,未初始化的数据存储在 .bss 段中.我不明白的是为什么我们有未初始化变量的专用段?如果一个未初始化的变量在运行时被赋值,该变量是否仍然只存在于 .bss 段中?

What I know is that global and static variables are stored in the .data segment, and uninitialized data are in the .bss segment. What I don't understand is why do we have dedicated segment for uninitialized variables? If an uninitialised variable has a value assigned at run time, does the variable exist still in the .bss segment only?

在下面的程序中,a.data段,b.bss段> 段;那是对的吗?如果我的理解有误,请指正.

In the following program, a is in the .data segment, and b is in the .bss segment; is that correct? Kindly correct me if my understanding is wrong.

#include <stdio.h>
#include <stdlib.h>

int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
int b[20]; /* Uninitialized, so in the .bss and will not occupy space for 20 * sizeof (int) */

int main ()
{
   ;
}  

另外,考虑下面的程序,

Also, consider following program,

#include <stdio.h>
#include <stdlib.h>
int var[10];  /* Uninitialized so in .bss */
int main ()
{
   var[0] = 20  /* **Initialized, where this 'var' will be ?** */
}

推荐答案

原因是为了减少程序大小.想象一下,您的 C 程序运行在嵌入式系统上,其中代码和所有常量都保存在真正的 ROM(闪存)中.在此类系统中,在调用 main() 之前,必须执行初始向下复制"以设置所有静态存储持续时间对象.它通常会像这个伪:

The reason is to reduce program size. Imagine that your C program runs on an embedded system, where the code and all constants are saved in true ROM (flash memory). In such systems, an initial "copy-down" must be executed to set all static storage duration objects, before main() is called. It will typically go like this pseudo:

for(i=0; i<all_explicitly_initialized_objects; i++)
{
  .data[i] = init_value[i];
}

memset(.bss, 
       0, 
       all_implicitly_initialized_objects);

其中 .data 和 .bss 存储在 RAM 中,而 init_value 存储在 ROM 中.如果是一个段,那么 ROM 就必须填满很多零,这会显着增加 ROM 的大小.

Where .data and .bss are stored in RAM, but init_value is stored in ROM. If it had been one segment, then the ROM had to be filled up with a lot of zeroes, increasing ROM size significantly.

基于 RAM 的可执行文件的工作方式类似,但它们当然没有真正的 ROM.

RAM-based executables work similarly, though of course they have no true ROM.

此外,memset 可能是一些非常高效的内联汇编器,这意味着可以更快地执行启动复制.

Also, memset is likely some very efficient inline assembler, meaning that the startup copy-down can be executed faster.

这篇关于为什么需要 .bss 段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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