如果一个全局变量初始化为0,它会去BSS? [英] If a global variable is initialized to 0, will it go to BSS?

查看:1294
本文介绍了如果一个全局变量初始化为0,它会去BSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有初始化的全局/静态变量会去的初始化的数据段的。
所有未初始化的全局/静态变量会去的 uninitialed数据部分的(BSS)。在BSS中的变量会在程序加载时间得到一个值0。

如果有一个全局变量明确初始化为零( INT myglobal = 0 ),其中变量将被保存?


解决方案

编译器就可以把这种可变进 BSS 以及到数据。例如,GCC有控制这种行为特殊选项:


  

-fno-零初始化功能于BSS


  
  

如果目标支持BSS段,GCC默认把被初始化为零到BSS变量。这个
  可以在生成的code节省空间。这个选项关闭此
  行为,因为某些程序明确依赖变量去
  的数据部分。例如,使生成的可执行文件可以找到
  开始的那款及/或使基于该假设。


  
  

默认为 -fzero初始化功能于BSS


在下面的例子试图( test.c以文件):

  INT put_me_somewhere = 0;INT主(INT ARGC,CHAR *的argv []){返回0; }

不带选项(隐含 -fzero初始化功能于BSS )编译

  $触摸test.c的&放大器;&安培;使测试&放大器;&安培; objdump的-x测试| grep的put_me_somewhere
CC test.c以-o测试
0000000000601028克Ø.bss中0000000000000004 put_me_somewhere

与编译 -fno-零初始化功能于BSS 选项:

  $触摸test.c的&放大器;&安培;使测试CFLAGS = -fno零初始化,在BSS&放大器;&安培; objdump的-x测试| grep的put_me_somewhere
CC -fno零初始化功能于BSS test.c的-o测试
0000000000601018克Ø。数据0000000000000004 put_me_somewhere

All the initialized global/static variables will go to initialized data section. All the uninitialized global/static variables will go to uninitialed data section(BSS). The variables in BSS will get a value 0 during program load time.

If a global variable is explicitly initialized to zero (int myglobal = 0), where that variable will be stored?

解决方案

Compiler is free to put such variable into bss as well as into data. For example, GCC has a special option controlling such behavior:

-fno-zero-initialized-in-bss

If the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code. This option turns off this behavior because some programs explicitly rely on variables going to the data section. E.g., so that the resulting executable can find the beginning of that section and/or make assumptions based on that.

The default is -fzero-initialized-in-bss.

Tried with the following example (test.c file):

int put_me_somewhere = 0;

int main(int argc, char* argv[]) { return 0; }

Compiling with no options (implicitly -fzero-initialized-in-bss):

$ touch test.c && make test && objdump -x test | grep put_me_somewhere
cc     test.c   -o test
0000000000601028 g     O .bss   0000000000000004              put_me_somewhere

Compiling with -fno-zero-initialized-in-bss option:

$ touch test.c && make test CFLAGS=-fno-zero-initialized-in-bss && objdump -x test | grep put_me_somewhere
cc -fno-zero-initialized-in-bss    test.c   -o test
0000000000601018 g     O .data  0000000000000004              put_me_somewhere

这篇关于如果一个全局变量初始化为0,它会去BSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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