In this lesson, you will learn how to direct constant data to non-volatile FLASH memory to keep your precious RAM available for dynamic variables.
Why Const Matters
In embedded systems, RAM is often the most restricted resource. When you define a variable like const char greeting[] = "Hello World!";, the compiler identifies that this data should never change. By default, the linker script might try to reserve space for this in RAM, consuming bytes that could be used for your stack or heap. To prevent this, we must ensure the linker places these "read-only" sections specifically into the FLASH memory region defined in your memory map.
The Linker Strategy
To handle this, we use the linker script to capture all sections containing constant data and force them into the FLASH memory region. In your linker script, you typically look for the .rodata (read-only data) section. You instruct the linker to map this section into the physical address space corresponding to your FLASH memory, rather than your RAM.
Consider this snippet from a typical linker script:
SECTIONS
{
.text :
{
*(.vectors)
*(.text*)
*(.rodata*) /* All constant data is gathered here */
} > FLASH
}
By placing *(.rodata*) inside the block assigned to the FLASH memory region (defined via the MEMORY command), you ensure that the constant data is burned into the chip's internal flash storage.
Benefits for Bare-Metal Systems
When data is placed in FLASH, the CPU reads it directly from the memory bus without needing a copy operation at startup. If you mistakenly placed this data in a section destined for RAM, the startup code (the C runtime) would waste time and memory copying these constants from FLASH to RAM during initialization—a process intended only for mutable global variables. By correctly segmenting your constants into FLASH-linked sections, you reduce your system's RAM footprint and eliminate unnecessary data movement, leaving more headroom for your application logic.
Key Takeaway: By mapping the .rodata section to the FLASH memory region in your linker script, you conserve limited RAM and prevent unnecessary overhead during system startup.