I am facing a problem while making a code more general, I want to replace hardcoded values with macro but I am facing this issue :
Original code :
#define io_dir_in(port, pin) NRF_P##port->PIN_CNF[pin] = (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos)
io_dir_in(0, 0);
I added :
#define A_Port 0
#define A_Pin 0
And replaced :
io_dir_in(A_Port, A_Pin);
But I get the error identifer "NRF_PA_Port" is undefined
because NRF_P
and A_Port
are getting concatenated.
Anyway to make it work ?
CodePudding user response:
The problem is that "concatenation of tokens" is done before an expansion of tokens. You need to add an extra step of expansion in between.
#define io_dir_in_impl(port, pin) NRF_P##port->PIN_CNF[pin] = (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos)
#define io_dir_in(port, pin) io_dir_in_impl(port, pin)
Now before io_dir_in_impl()
is expanded all its arguments are expanded. Thus A_Port
will be replaced with 0
.
With this tweak io_dir_in(A_Port, A_Pin);
expands as:
NRF_P0->PIN_CNF[0] = (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos);