不同文件中同名的静态变量 [英] Static variable with the same name in different file

查看:78
本文介绍了不同文件中同名的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行和编译代码,其中我在两个不同的源文件中定义了具有相同名称的 静态变量.代码编译成功并运行.

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.

现在我的问题是这两个静态变量都驻留在内存中的 .data/BSS 部分.根据我的理解,两个不同的内存位置必须有一个单独的唯一名称标识符.为什么在这种情况下这不是问题?

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?

推荐答案

根据我的理解,两个不同的内存位置必须有一个单独的唯一名称标识符."- 在这种情况下,不清楚您所说的内存位置"是什么意思.内存位置有地址,而不是名称.如果内存位置"是指单个变量",那么上述语句仅适用于具有外部链接的变量.具有外部链接的变量需要外部可见的名称.带有内部链接的变量(静态变量)没有.

"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.

附言在 C++ 语言中,带有外部链接的内联函数允许在内部定义静态变量.为了提供适当的功能,编译器通常为此类静态变量分配外部名称.也支持内联函数的 C 语言决定以不同的方式处理这个问题:在 C 语言中,内联函数定义被简单地禁止包含静态变量定义.

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.

这篇关于不同文件中同名的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆