In this lesson, you will learn how to manually move your initialized global variables from permanent Flash memory into volatile RAM so they are ready for use when your program begins execution.
The Memory Duality
When you declare a global variable like int counter = 42; in C, the compiler needs to store that value of 42 somewhere that won't disappear when the power turns off. That location is your Flash memory (the .data section). However, your CPU cannot modify data inside Flash—it needs that variable to live in RAM so it can increment or change it during runtime.
The Role of the Startup Sequence
Since RAM is cleared (or contains garbage data) at power-on, the CPU must perform a "copy" operation before it ever enters your main() function. This is the responsibility of the Reset Handler.
To do this, the linker script provides two specific markers (often called symbols):
- Flash Start Address (
_sidata): Where the initial values are sitting in Flash. - RAM Start/End Addresses (
_sdata,_edata): Where those values need to live in RAM.
Implementing the Copy Logic
Inside your startup code, you use these addresses to move the data byte-by-byte or word-by-word. It looks conceptually like this:
// Pointers to the memory regions defined in the linker script
extern uint32_t _sidata; // Start of data in Flash
extern uint32_t _sdata; // Start of data in RAM
extern uint32_t _edata; // End of data in RAM
void initialize_data_section(void) {
uint32_t *flash_ptr = &_sidata;
uint32_t *ram_ptr = &_sdata;
// Copy until we reach the end of the RAM data section
while (ram_ptr < &_edata) {
*ram_ptr = *flash_ptr;
ram_ptr++;
flash_ptr++;
}
}
By running this loop during the early reset sequence, you ensure that every variable initialized with a value at compile-time is physically present in RAM before the logic of your application starts. If you skip this, your counter variable will simply hold whatever random noise was in that RAM address at startup, leading to unpredictable program behavior.
Key Takeaway: The CPU must bridge the gap between non-volatile Flash storage and volatile RAM by executing a manual copy routine for all initialized global variables during the startup process.