</>EmbeddedInterview

How do you place a variable or function at a specific address or section?

MediumEmbedded C

Short answer: Put it in a named section with __attribute__((section(".name"))) and map that section to the right memory region (or address) in the linker script. For a fixed absolute address, define the section at that address in the script, or (for read-only/hardware addresses) use a pointer to that address instead of a variable.

/* code that must run from RAM, e.g. while flash is being erased */
__attribute__((section(".ramfunc"), noinline, long_call))
void flash_erase_sector(uint32_t sector) { /* ... */ }

/* data kept across a warm reset (not zeroed at start-up) */
__attribute__((section(".noinit"))) uint32_t reset_count;

/* firmware header at a fixed offset, read by the bootloader */
__attribute__((section(".fw_header"), used))
const struct fw_header hdr = { .magic = 0x46574844u, .version = 0x010200u };

/* DMA buffer in a non-cacheable, DMA-reachable SRAM bank, cache-line aligned */
__attribute__((section(".dma_buf"), aligned(32))) uint8_t adc_buf[1024];
.ramfunc : { _sramfunc = .; *(.ramfunc*) _eramfunc = .; } > RAM AT> FLASH   /* copied at start-up */
.noinit (NOLOAD) : { *(.noinit*) } > RAM
.fw_header 0x08008200 : { KEEP(*(.fw_header)) } > FLASH
.dma_buf (NOLOAD) : { *(.dma_buf*) } > SRAM_D2

Why code runs from RAM: on most MCUs you cannot read (execute from) a flash bank while it is being erased or programmed; the CPU stalls or faults. Placing the flash-programming routine (and everything it calls, and the interrupt handlers that may run) in RAM avoids this. long_call makes calls between RAM and flash work when they are further apart than a branch instruction can reach.

Other mechanisms

  • used / KEEP() stop the compiler and linker from removing data nothing references.
  • IAR uses @ placement (int x @ 0x20001000;) and #pragma location; Keil has __attribute__((at(addr))) in older versions.
  • For hardware registers, never declare a variable; use a pointer constant: #define REG (*(volatile uint32_t *)0x40021000u).

Verify in the map file that the symbol landed where you expected.