Substitute just once, concatenate, and substitute again

Viewed 31

Given macro definitions like this:

#define GPIOA ((1234)+42)
#define GPIOB ((1234)+84)

#define LEDA_GPIO_Port GPIOA
#define LEDB_GPIO_Port GPIOB

#define MY_PORT_GPIOA 0
#define MY_PORT_GPIOB 1

I would like to define a macro MY_PORT which, given LEDA as argument somehow substitutes this to LEDA_GPIO_Port, then to GPIOA, turns that into MY_PORT_GPIOA and this into 0. So MY_PORT(LEDA) should evaluate to 0 and MY_PORT(LEDB) to 1. If the macros GPIOA/GPIOB wouldn't exist, this would be easy, but since they are defined as complex expressions (starting with parentheses) only one substitution must be performed, and the occurence of GPIOA must not be substituted by that expression.

I tried

#define MY_PORT2(port) MY_PORT_##port
#define MY_PORT(name) MY_PORT2(name##_GPIO_Port)

but here MY_PORT(LEDA) returns MY_PORT_LEDA_GPIO_Port, i.e. it lacks one substituion.

#define CONCAT(a,b) a##b
#define MY_PORT2(port) CONCAT(MY_PORT,port)
#define MY_PORT(name) MY_PORT2(name##_GPIO_Port)

does not compile, as it tries to concatenate the definition for GPIOA, i.e. one subtitution too many.

Is it even possible to do exactly one subtitution?

0 Answers
Related