Where are static variables stored in C and C++?

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.


Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA


When a program is loaded into memory, it’s organized into different segments. One of the segment is DATA segment. The Data segment is further sub-divided into two parts:

  • Initialized data segment: All the global, static and constant data are stored here.
  • Uninitialized data segment (BSS): All the uninitialized data are stored in this segment.

Here is a diagram to explain this concept:

enter image description here

Here is very good link explaining these concepts: Memory Management in C: The Heap and the Stack