Search code examples
ccompiler-constructionstatic

how compiler will identify which static variable to read or update?


Below is my code:

#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()
}

Now in this program compiler will store both variable a to data segment(bss segment to be precise), so if both variables goes to same segment, how compiler will identify which one to access when user wants to change or read any one of them.

For example, if user wants to change the value of variable a which is inside main(), how compiler will identify which 'a' to change in data segment memory.


Solution

  • The compiler knows which static variable you need by context. One way to differentiate the actual variables is by mangling the names. I tried a slightly modified version of your program:

    #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;
    }
    

    If you run the source through the ELLCC demo page (don't forget to turn off optimization!), you can look at what the compiler generates for your favorite target processor. In the assembly language, you can see that the compiler creates two variables: a and main.a. The ELLCC compiler is based on clang/LLVM, but other compilers will do similar tricks.

    Looking at a compiler's assembly output is a great way to answer questions like this.