In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision? For example:
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);
} }
If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.
But where is the storage allocated?
To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I believe that there has to be some space reserved in the executable file for those static variables.
For discussion purposes, lets assume we use the GCC toolchain.
How to find it yourself with
objdump -Sr
To actually understand what is going on, you must understand linker relocation. If you've never touched that, consider reading this post first.
Let's analyze a Linux x86-64 ELF example to see it ourselves:
Compile with:
Decompile the code with:
-S
decompiles the code with the original source intermingled-r
shows relocation informationInside the decompilation of
f
we see:and the
.data-0x4
says that it will go to the first byte of the.data
segment.The
-0x4
is there because we are using RIP relative addressing, thus the%rip
in the instruction andR_X86_64_PC32
.It is required because RIP points to the following instruction, which starts 4 bytes after
00 00 00 00
which is what will get relocated. I have explained this in more detail at: https://stackoverflow.com/a/30515926/895245Then, if we modify the source to
i = 1
and do the same analysis, we conclude that:static int i = 0
goes on.bss
static int i = 1
goes on.data
in the "global and static" area :)
there are several memory area in C++
see here for detailed answer to your question
This is how (easy to understand):
Well this question is bit too old, but since nobody points out any useful information: Check the post by 'mohit12379' explaining the store of static variables with same name in the symbol table: http://www.geekinterview.com/question_details/24745