下面是我的代码:
#include <stdio.h>
static int a; // this static variable scope is through out the file
int main()
{
static int a; // this static variable scope is only in main()
}
现在,在这个程序中,编译器会将两个变量 a 存储到数据段(准确地说是 bss 段),因此,如果两个变量都存储在同一段中,当用户想要更改或读取任何一个时,编译器将如何识别要访问哪一个变量其中。
例如,如果用户想要更改 main() 内部变量 a 的值,编译器将如何识别数据段内存中的哪个“a”要更改。
最佳答案
编译器通过上下文知道你需要哪个静态变量。区分实际变量的一种方法是修改名称。我尝试了对您的程序进行了稍微修改的版本:
#include <stdio.h>
static int a; // this static variable scope is through out the file
int main()
{
static int a; // this static variable scope is only in main()
a=1;
}
void f()
{
a = 2;
}
如果您通过 ELLCC demo page 运行源代码(不要忘记关闭优化!),您可以查看编译器为您最喜欢的目标处理器生成的内容。在汇编语言中,您可以看到编译器创建了两个变量:a和main.a。 ELLCC编译器基于clang/LLVM,但其他编译器也会做类似的技巧。
查看编译器的汇编输出是回答此类问题的好方法。
关于c - 编译器如何识别要读取或更新哪个静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448184/