Static variable with the same name in different file [duplicate]

自闭症网瘾萝莉.ら 提交于 2021-02-05 09:29:21

问题


I have tried running and compiling the code where I have defined the static variables with the same name in two different source files. The code was compiled successfully and running.

Now my question is that both the static variables reside in the .data/BSS section in the memory. As per my understanding two different memory locations must have a separate unique name identifier. Why this was not a problem in this case?


回答1:


"As per my understanding two different memory locations must have a separate unique name identifier." - it is not clear what you mean by "memory locations" in this case. Memory locations have addresses, not names. If by "memory locations" you mean "individual variables", then the above statement only applies to variables with external linkage. Variables with external linkage need externally visible names. Variables with internal linkage (static variables) don't.

In a typical implementation all static symbols are resolved internally by the compiler, at the compilation stage. They do not produce external names in object files. I.e they are not exposed to the linker at all. In the simplest case all static variables from the same translation unit are are seen by the linker as a single blob of data.

By the time different translation units are brought together for linking, all names of static variables are no longer necessary. By that time they are long forgotten. Which is why naming conflicts do not have a chance to occur.

P.S. In C++ language inline functions with external linkage are allowed to define static variables inside. To provide proper functionality, compilers typically assign external names to such static variables. C language, which also supports inline functions, decided to deal with this matter differently: in C language inline function definitions are simply prohibited to contain static variable definitions.



来源:https://stackoverflow.com/questions/25941062/static-variable-with-the-same-name-in-different-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!