Where are static variables stored in C and C++?

前端 未结 16 2464
自闭症患者
自闭症患者 2020-11-22 02:00

In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don\'t have name collision? For example:


foo.c:                  


        
16条回答
  •  深忆病人
    2020-11-22 02:43

    I don't believe there will be a collision. Using static at the file level (outside functions) marks the variable as local to the current compilation unit (file). It's never visible outside the current file so never has to have a name that can be used externally.

    Using static inside a function is different - the variable is only visible to the function (whether static or not), it's just its value is preserved across calls to that function.

    In effect, static does two different things depending on where it is. In both cases however, the variable visibility is limited in such a way that you can easily prevent namespace clashes when linking.

    Having said that, I believe it would be stored in the DATA section, which tends to have variables that are initialized to values other than zero. This is, of course, an implementation detail, not something mandated by the standard - it only cares about behaviour, not how things are done under the covers.

提交回复
热议问题