简体   繁体   中英

compose the name of the argument in the C macro

I have a task to activate many pins of the microcontroller for input. Obviously, it is possible to call the initialization function for each pin, which I am limited to.

board_pins_init(BUT1_PIN, BUT1_PORT, GPIO_MODE_DIGITAL_IN, 0, GPIO_MODE_NP);

And I'm trying to automate it like this

#define INIT_BUTTON(num) \
board_pins_init(BUT##num##_PIN, BUT##num##_PORT, GPIO_MODE_DIGITAL_IN, 0, GPIO_MODE_NP);

...

for(int i = 0; i<MAX_BUTTONS_QTY; i++)
    INIT_BUTTON(i)

in this case, the compiler returns an error 'BUTi_PORT' undeclared (first use in this function it turns out that instead of the value i, the compiler substitutes the symbol 'i'

how do I write a macro correctly?

First of all, unless the amount of these lines are, fast, what you already have is the far superior KISS version:

board_pins_init(BUT0_PIN, BUT0_PORT, GPIO_MODE_DIGITAL_IN, 0, GPIO_MODE_NP);
board_pins_init(BUT1_PIN, BUT1_PORT, GPIO_MODE_DIGITAL_IN, 0, GPIO_MODE_NP);
board_pins_init(BUT2_PIN, BUT2_PORT, GPIO_MODE_DIGITAL_IN, 0, GPIO_MODE_NP);

Assuming you can't write readable code like that for some reason, then...

Since macros are only evaluated at compile-time and variables only exist in run-time, you cannot generate macro names based on variable values.

In this case it would seem that "X macros" might solve your actual problem:

// a list of all button numbers
#define BUTTON_LIST(X) \
  X(0)                 \
  X(1)                 \
  X(2)                 \

...

#define INIT_BUTTON(n)                   \
  board_pins_init(BUT##n##_PIN,          \
                  BUT##n##_PORT,         \
                  GPIO_MODE_DIGITAL_IN,  \
                  0,                     \
                  GPIO_MODE_NP);
BUTTON_LIST(INIT_BUTTON)

This works just fine for ports called A, B, C or whatever too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM