Do .bss section zero initialized variables occupy space in elf file?

后端 未结 4 2117
有刺的猬
有刺的猬 2020-12-04 08:44

If I understand correctly, the .bss section in ELF files is used to allocate space for zero-initialized variables. Our tool chain produces ELF files, hence my q

4条回答
  •  醉梦人生
    2020-12-04 09:00

    The .bss section in an ELF file is used for static data which is not initialized programmatically but guaranteed to be set to zero at runtime. Here's a little example that will explain the difference.

    int main() {
        static int bss_test1[100];
        static int bss_test2[100] = {0};
        return 0;
    }
    

    In this case bss_test1 is placed into the .bss since it is uninitialized. bss_test2 however is placed into the .data segment along with a bunch of zeros. The runtime loader basically allocates the amount of space reserved for the .bss and zeroes it out before any userland code begins executing.

    You can see the difference using objdump, nm, or similar utilities:

    moozletoots$ objdump -t a.out | grep bss_test
    08049780 l     O .bss   00000190              bss_test1.3
    080494c0 l     O .data  00000190              bss_test2.4
    

    This is usually one of the first surprises that embedded developers run into... never initialize statics to zero explicitly. The runtime loader (usually) takes care of that. As soon as you initialize anything explicitly, you are telling the compiler/linker to include the data in the executable image.

提交回复
热议问题