Home / Learn Embedded C / Modeling Registers as C Structs

Modeling Registers as C Structs

How vendor headers group a peripheral's registers into one struct matching its real memory layout.

Bottom lineHow vendor headers group a peripheral's registers into one struct matching its real memory layout.

Breaking it down

What it is

Vendor headers commonly define a struct whose members are laid out in exactly the same order and size as a peripheral's real registers in memory, then "overlay" that struct onto the peripheral's base address, letting code write GPIOA->MODER instead of a raw address.

Why it matters

This is purely a readability and maintainability convenience — GPIOA->ODR is far clearer to a human reader than a raw hex address, even though both ultimately access the exact same memory location.

Mechanically speaking

The struct's member order and padding must exactly match the real hardware register layout (in bytes and order) — an incorrect struct definition (even a reordered or missing member) silently corrupts which register each access actually hits.

Shows up in

  • Reading vendor SDK headers
  • Driver code organization
  • STM32/similar chip-family code

Try it

The same idea with plain variables standing in for each struct memberC: edit and run

Three separate variables here stand in for the three struct members GPIOA->MODER, GPIOA->OTYPER and GPIOA->ODR.

Careful:This course's sandbox cannot execute struct syntax (documented in JSCPP_NOTES.md), so the listing below is reference-only — this is purely how real vendor headers are structured, for recognition when reading real code.
A typical register struct overlay (reference only — not runnable in this sandbox)
typedef struct {
    volatile unsigned int MODER;
    volatile unsigned int OTYPER;
    volatile unsigned int ODR;
} GPIO_TypeDef;

#define GPIOA ((GPIO_TypeDef*)0x40020000)
/* usage: GPIOA->ODR |= (1 << 5); */

Try it: a second peripheral modeled the same way

Plain variables standing in for a second peripheral's "struct members"C: edit and run

Just as GPIOA->ODR stood for one register, these three variables stand for TIM2->CR1, TIM2->ARR and TIM2->CNT in a real timer struct overlay.

Check yourself

1. What must be true for a register struct overlay to correctly access real hardware?