gpt4 book ai didi

c - 如果一个全局变量初始化为0,它会去BSS吗?

转载 作者:太空狗 更新时间:2023-10-29 16:24:25 24 4
gpt4 key购买 nike

所有初始化的全局/静态变量将转到初始化数据部分。所有未初始化的全局/静态变量将转到未初始化的数据部分(BSS)。 BSS 中的变量在程序加载期间将获得值 0。

如果全局变量显式初始化为零(int myglobal = 0),该变量将存储在哪里?

最佳答案

编译器可以自由地将此类变量放入bss 以及data 中。例如,GCC 有一个 special option控制此类行为:

-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.

尝试使用以下示例(test.c 文件):

int put_me_somewhere = 0;

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

无选项编译(隐式 -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

使用 -fno-zero-initialized-in-bss 选项编译:

$ 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

关于c - 如果一个全局变量初始化为0,它会去BSS吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com