c - 编译器如何识别要读取或更新哪个静态变量?

标签 c compiler-construction static

下面是我的代码:

#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 运行源代码(不要忘记关闭优化!),您可以查看编译器为您最喜欢的目标处理器生成的内容。在汇编语言中,您可以看到编译器创建了两个变量:ama​​in.a。 ELLCC编译器基于clang/LLVM,但其他​​编译器也会做类似的技巧。

查看编译器的汇编输出是回答此类问题的好方法。

关于c - 编译器如何识别要读取或更新哪个静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448184/

相关文章:

delphi - 编译器指令 - Delphi 版本

c - 无法识别 Lex 中的单行注释

c# - 线程竞速,为什么线程这么工作?

static - 不能借用不可变的 'Box' 内容作为可变的

java - 创建自己的 Android Java 库

c - 释放在 2D 结构中分配的内存

集群上带有 SLURM 的 C 库函数 exit()

c++ - C++ 中的常量混淆

c - 在 pthreads 原始套接字中接收数据包

java - 如何使用 Getopt 在不带前导连字符的情况下解析参数