Sections and variables initialization
Default init
ANSI C requires all uninitialized static and global variables to be initialized with 0 (ยง6.7.8 of the C99 definition). This means you can rely on the following behavior:
int global;
void function() {
printf("%d\n",global);
}
This will print 0, and it is guaranteed by the standard.
However, this is not handled by the compiler. All you will be able to see is that the variable is put in the bss section:
08049560 l O .bss 00000004 static_var.1279
08049564 g O .bss 00000004 global_var
It is the startup code of the linker which initializes the variables.
The C compiler usually puts variables that are supposed to be initialized with 0 in the .bss section instead of the .data section. Opposed to the .data section, the .bss section does not contain actual data, it just specifies the size of all elements it contains. The C compiler just *assumes* that the linker, loader, or the startup code of the C library initializes this block of memory with 0. This is an optimization; .data elements occupy space in the image (or ROM or flash memory) and in RAM whereas .bss elements need to occupy RAM space only if they are initialized at run-time.
(Gcc provides even an option (-fno-zero-initialized-in-bss
) to do not
rely on this optimization, that is, to put all 0-initialized elements
into the .data section as well.
You can use
__attribute__((section, ".mysection"))
on every uninitialized variable to instruct the compiler to put it into your own section.