1

Let say I have defined two static variables(having same name) in two different files, these will be stored in bss section.

//File1.c
static int st;

//File2.c
static int st;

But how differentiation is made between them that which one belongs to which file at run time.

I found couple of topics here but not answering my question -

  1. Two static variables in same name(two different file) and extern one of them in any other file

  2. Where are static variables stored (in C/C++)?

Community
  • 1
  • 1
µtex
  • 900
  • 5
  • 12
  • 3
    `But how differentiation is made between them that which one belongs to which file at run time.` .. that's the function of the compiler and linker. Read [this answer](http://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-c/109120#109120) from the 2nd link you posted, talks about scope. – txtechhelp Jul 25 '16 at 05:15
  • Great.. convincing... – µtex Jul 25 '16 at 05:22

1 Answers1

2

There is no need for a name at runtime. The name is only necessary for you and the C compiler. The C compiler knows to which file it belongs, the file where it's defined. That's enough information.

Both variables are stored in the .bss section with their respective name, but at different memory locations. That's how their distinction is made.

You can confirm yourself how they are stored by using objdump:

$ cat foo1.c
static int foo = 1;

$ cat foo2.c
static int foo = 2;

$ cat main.c
int main(void) { return 0; }

$ gcc -g -O0 -o foo foo1.c foo2.c main.c

$ objdump -d -j .data foo
test:     file format elf64-x86-64


Disassembly of section .data:

00000000006008a8 <foo>:
  6008a8:   01 00 00 00                                         ....

00000000006008ac <foo>:
  6008ac:   02 00 00 00                                         ....
Leandros
  • 16,805
  • 9
  • 69
  • 108