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.
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
Three separate variables here stand in for the three struct members GPIOA->MODER, GPIOA->OTYPER and GPIOA->ODR.
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
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?
Since the struct is overlaid directly onto a fixed memory address, any mismatch between its layout and the real hardware registers would make each member access hit the wrong physical register.