Local and static variables in C

前端 未结 3 520
-上瘾入骨i
-上瘾入骨i 2021-02-05 08:51

When compiling this:

// external definitions
int value1 = 0;
static int value2 = 0;

the gcc compiler generates the following assembly:

3条回答
  •  滥情空心
    2021-02-05 09:20

    Generally speaking, the bss section contains uninitialized values and the data section contains initialized values. However, gcc places values that are initialized to zero into the bss section instead of the data section, as the bss section is zeroed out in runtime anyway, it doesn't make much sense to store zeros in the data section, this saves some disk space, from man gcc:

    -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

    I'm not sure why .comm is used with static storage which is local to an object file, it is usually used to declare common symbols that, if not defined/initialized, should be merged by the linker with symbol that have the same name from other object files and that's why it's not used in the second example because the variables are initialized, from the as manual

    .comm declares a common symbol named symbol. When linking, a common symbol in one object file may be merged with a defined or common symbol of the same name in another object file

提交回复
热议问题