I’m writing code for a specific stm32 chip with memory mapped peripherals. I happen to know that one of the GPIO ports, GPIOA
, is controlled by several 32 bit ints located starting at address 0x40018000
. How can I express this information at compile time?
My initial attempt looked like this:
struct Gpio {
volatile uint32_t crl;
volatile uint32_t crh;
// ...
};
constinit Gpio& GPIOA = *reinterpret_cast<Gpio*>(0x40018000);
This seems like a sensible way to say “The reference GPIOA
refers to an object located at memory address 0x40018000
Unfortunately this does not work:
error: 'constinit' variable 'GPIOA' does not have a constant initializer
error: 'reinterpret_cast' from integer to pointer
What options are available to me? How can I spell a specific numeric memory address at compile time?
Prior research:
- Is it possible to have a pointer literal?
- It is not possible to have a pointer literal.
- How to place a variable at a given absolute address in memory (with GCC)
- Globals can be placed at specific addresses using linker scripts.
- This happens at link time, not compile time.