What actually compiler does when we declare static variables?

后端 未结 4 1598
既然无缘
既然无缘 2021-01-05 07:58

I want to know what actually going under the hood,how compiler treats static variables. Unlike auto variable, static variable\'s value persist even after the end of block bu

4条回答
  •  没有蜡笔的小新
    2021-01-05 08:48

    Typical C compilers produce assembly output that creates four "sections" of memory. The linker/loader generally combines various items labelled with the same section together as it loads the program into memory. The most common sections are:

    "text": This is actual program code. It is considered read-only (linker/loader on some machines might place it in ROM, for example).

    "data": This is simply an allocated area of RAM, with initial values copied from the executable file. The loader will allocate the memory, then copy in its initial contents.

    "bss": Same as data, but initialized to zeros.

    "stack": Simply allocated by the loader for its program stack.

    Global and static variables are placed in "data" and "bss", and therefore have a lifetime of the life of the program. Static variables do not, however, place their names in the symbol table, so they can't be linked externally like globals. Visibility and lifetime of variables are totally separate concepts: C's syntax confuses the two.

    "Auto" variables are typically allocated on the stack during program execution (though if they are very large, they may be allocated on the heap instead). They only exist within their stack frame.

提交回复
热议问题