Is it possible to declare several static variables with the same name in a single C file?


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++)
    printf("sVar = %d\n", sVar);

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?

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

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.