Where are static variables stored in C and C++?
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:
Here is very good link explaining these concepts: Memory Management in C: The Heap and the Stack
In fact, a variable is tuple (storage, scope, type, address, value):
storage : where is it stored, for example data, stack, heap...
scope : who can see us, for example global, local...
type : what is our type, for example int, int*...
address : where are we located
value : what is our value
Local scope could mean local to either the translational unit (source file), the function or the block depending on where its defined. To make variable visible to more than one function, it definitely has to be in either DATA or the BSS area (depending on whether its initialized explicitly or not, respectively). Its then scoped accordingly to either all function(s) or function(s) within source file.
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
The storage location of the data will be implementation dependent.
However, the meaning of static is "internal linkage". Thus, the symbol is internal to the compilation unit (foo.c, bar.c) and cannot be referenced outside that compilation unit. So, there can be no name collisions.