Local and static variables in C

前端 未结 3 580
-上瘾入骨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:21

    The first case is because you initialized the values with zero. It's part of the C standard (section 6.7.8) that a global integer gets initialized with 0 if none is specified. So file formats made a provision to keep binaries smaller by having a special section these get placed in: bss. If you take a look at some of the ELF specification (on page I-15), you'll find this:

    .bss This section holds uninitialized data that contribute to the program's memory image. By definition, the system initializes the data with zeros when the program begins to run. The section occupies no file space, as indicated by the section type, SHT_NOBITS.

    In the first case, the compiler made an optimization. It doesn't need to take up room in the actual binary to store the initializer, since it can use the bss segment and get the one you want for free.

    Now, the fact that you have a static coming in from an external source is a bit interesting (it's not typically done). In the module being compiled though, that should not be shared with other modules, and should be marked with .local. I suspect it does it this way because there is no actual value to be stored for the initializer.

    In the second example, because you've given a non-zero initializer, it know resides in the initialized data segment data. value1 looks very similar, but for value2, the compiler needs to reserve space for the initializer. In this case, it doesn't need to be marked as .local because it can just lay down the value and be done with it. It's not global because there is no .globl statement for it.

    BTW, http://refspecs.linuxbase.org/ is a good place to visit for some of the low-level details about binary formats and such.

提交回复
热议问题