Search code examples
pointersmacrosembeddedavr

Preprocessor Macro : Make pointer from integer content


I would like to make a preprocessor macro which converts an integer representing an address into a pointer. This is for MCU development.

For example, registers are defined like

#define SOME_REGISTER 0x05 // This the the address of SOME_REGISTER

So I have defined the following macro:

#define REG_ADDR(reg) (*((volatile uint8_t*) reg))

And when I wan't to use it

volatile uint8_t * reg_ptr = REG_ADDR(SOME_REGISTER)

But of course, I get the makes pointer from integer without a cast [-Wint-conversion] warning

Is there a clean way to do that ?

Thanks by advance


Solution

  • Normally, you'd simply define such registers as #define SOME_REGISTER (*(volatile uint8_t*) 0x05) without the extra step.

    The compiler message comes because the macro is written with a * de-reference so that it can be used just as a regular variable. So you'd read/write directly to the register, without no local pointer variable in between.

    If that's not what you want, then either don't use the register like that, or change the code to this:

    volatile uint8_t* reg_ptr = &REG_ADDR(SOME_REGISTER);
    

    The & at the caller and the * inside the macro will cancel each other out.