loneRanger
loneRanger

Reputation: 841

Preprocessor macros substitution

#define LED1_ON() { /* twiddle port bit */ }
#define LED2_ON() { /* twiddle port bit */ }
//  ...
#define LED9_ON() { /* twiddle port bit */ }

#define LED_ON(x) LED##x_ON()

I would like to use the above code (or something similar) to have (for example) LED_ON(1) call macro LED1_ON(), or LED_ON(2) call macro LED2_ON().

I believe it is possible to make cpp do this, but clearly I don't have the syntax correct. Does anyone know the syntax to make this possible?

On the line where I call the LED_ON(2), gcc gives the error message:

undefined reference to `LEDx_ON'

Upvotes: 5

Views: 9342

Answers (3)

Alam
Alam

Reputation: 1596

Do something like this

#define LED_ON(num) \
    void LED_ON##num() \
    {\
        printf("set the bit for %d\n", num); \
    }\

LED_ON(1) 
LED_ON(2)

int main() {
    LED_ON1();
    LED_ON2();
}

LED_ON(1) and LED_ON(2) will be expanded to full function with name LED_ON1() and LED_ON2() And call functions as LED_ON1() LED_ON2()

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126478

You need to define LED_ON as

#define LED_ON(x)  LED##x##_ON()

you want to take the argument x and paste on an LED prefix and a _ON suffix.

Upvotes: 19

PiotrK
PiotrK

Reputation: 1552

I think that the preprocessor mechanism shouldn't be overused. If some more serious logic starts to appear in the macros, maybe it's time to switch to inline functions? They are more readable, just as fast, more powerful and you have some help from the compiler in case of parameter types aso..

If you insist on #define LED_ON(x) macro and subsequent LEDs are controlled by subsequent bits of one port, you can try something like this:

#define LED_ON(x)   SetBit(port, 1<<x);

Upvotes: 0

Related Questions