0

I have a global static variable 'x' defined in my program and I have local static variable 'x' defined in one function of same program. Both should be residing in Data segment. Then why the compiler is not giving error or how the names are resolved.

kadina
  • 5,042
  • 4
  • 42
  • 83
  • 1
    possible duplicate of [how refer to a local variable share same name of a global variable in C?](http://stackoverflow.com/questions/5827447/how-refer-to-a-local-variable-share-same-name-of-a-global-variable-in-c) – aruisdante Mar 12 '14 at 03:17
  • @aruisdante: Sorry. This is not duplicate of the question you posted. The question is how we can access global variable from a function which is already having same variable defined as static inside the function. This question is not at all similar to that. – kadina Mar 12 '14 at 17:32

2 Answers2

2

You are correct that both variables will be stored in the Data segment. However, these values are simply stored in two different offsets in that segment. The compiler differentiates between these two variables using scope, and based on that it converts it into the right offset.

thisisdog
  • 908
  • 1
  • 5
  • 13
2

why the compiler is not giving error

Because those two variables have different scope, which means they are two different variable from the viewpoint of a compiler.

how the names are resolved

Compiler may give them different names.

For example

static int x;

void foo(void) {
    static int x;
}

here is the symbols for both x:

$ readelf -s t108.o | grep x
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
     6: 0000000000000004     4 OBJECT  LOCAL  DEFAULT    3 x.1707
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47