编译器如何识别要读取或更新的静态变量?
how compiler will identify which static variable to read or update?
下面是我的代码:
#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,但其他编译器也会做类似的技巧。
查看编译器的汇编输出是回答此类问题的好方法。