</>EmbeddedInterview

What is the difference between a .bss and a .data section?

EasyC Programming

Short answer: .data holds global and static variables with non-zero initial values; the values are stored in flash and copied into RAM by the start-up code. .bss holds global and static variables that are zero or uninitialised; only its size is stored, and the start-up code fills that RAM with zeros. .rodata holds constants (in flash), and .text holds code.

int counter;                  /* .bss  (zero)                         */
int baud = 115200;            /* .data (initial value in flash, copy in RAM) */
static uint8_t buf[512];      /* .bss                                 */
const uint8_t lut[256] = {1}; /* .rodata (flash only)                 */
void f(void) { }              /* .text                                */
int x = 0;                    /* .bss: explicitly zero still goes in .bss with GCC */

Memory cost of each section on an MCU

Section Flash RAM
.text yes no
.rodata yes no
.data yes (initial values) yes (the variables)
.bss no yes
stack, heap no yes

Start-up code (simplified):

extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;   /* from the linker script */

void Reset_Handler(void)
{
    uint32_t *src = &_sidata, *dst = &_sdata;
    while (dst < &_edata) *dst++ = *src++;      /* copy .data from flash to RAM */
    for (dst = &_sbss; dst < &_ebss; ) *dst++ = 0;  /* zero .bss */
    SystemInit();
    main();
    for (;;) { }
}

Practical consequences

  • Making a large table const moves it from .data (flash and RAM) to .rodata (flash only). On a 20 KB RAM part this can be the difference between fitting and not fitting.
  • A big .bss makes boot slightly slower (zeroing) but costs no flash.
  • Variables that must survive a reset (e.g. a crash counter or a bootloader flag) go in a separate .noinit section that the start-up code does not touch.

Check sizes: arm-none-eabi-size firmware.elf prints text data bss. Flash used = text + data; RAM used = data + bss (plus stack and heap).