是否可以在单个 C 文件中声明多个具有相同名称的静态变量? [英] Is it possible to declare multiple static variables with same name in a single C file?
问题描述
是否可以在具有不同作用域的单个 C 文件中声明多个同名静态变量?我编写了一个简单的程序来检查这一点,并在 gcc 中编译并运行良好.
Is it possible to declare multiple static variables of same name in a single C file with different scopes? I wrote a simple programme to check this and in gcc it got compiled and worked fine.
代码:
static int sVar = 44;
void myPrint2()
{
printf("sVar = %d\n", sVar++);
}
void myPrint()
{
static int sVar =88;
printf("sVar = %d\n", sVar++);
}
int main(void)
{
static int sVar = 55;
int i = 0;
for (i = 0; i < 5; i++)
myPrint();
printf("sVar = %d\n", sVar);
myPrint2();
return(0);
}
现在我的问题是,由于所有静态"变量都将驻留在同一部分 (.data) 中,那么我们如何在一个部分中拥有多个具有相同名称的变量?
Now my question is since all "static" variable will reside in same section (.data) then how we can have multiple variables with same name in one section?
我使用objdump
检查不同的部分,发现所有静态变量(sVar
)都在.data部分,但名称不同:
I used objdump
to check the different section and found that all the static variables (sVar
) were in .data section but with different names:
0804960c l O .data 00000004 sVar
08049610 l O .data 00000004 sVar.1785
08049614 l O .data 00000004 sVar.1792
为什么编译器要更改变量的名称(因为 C 不支持名称修改)?
Why is the compiler is changing the name of the variables (since C doesn't support name mangling)?
推荐答案
函数局部静态变量与全局静态变量不同变量.
由于可以有尽可能多的具有相同名称的函数局部静态变量(假设它们都在不同的范围内),编译器可能必须在内部更改它们的名称(合并函数名称或行号或其他任何内容),因此链接器可以区分它们.
A function-local static variable is something different than a global static variable.
Since there can be as many function-local statics with the same name as you like (provided they are all in different scopes), the compiler might have to change their names internally (incorporating the function's name or the line number or whatever), so that the linker can tell them apart.
这篇关于是否可以在单个 C 文件中声明多个具有相同名称的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!