Search code examples
cgccmacrosc-preprocessoravr

Conditional macro definition


I tried the following syntax to define a macro:

#define SETBIT(ADDRESS,BIT,NEG)  #if NEG                    \
                                   (ADDRESS &= ~(1<<BIT))   \
                                 #else                      \
                                   (ADDRESS |= (1<<BIT))    \
                                 #endif

Using:

#define LED1 PORTA,1,1   \\ LED with anode to Vcc
#define LED2 PORTA,1,0   \\ LED with anode to GND
SETBIT(LED1)             \\ resulting in bit clear
SETBIT(LED2)             \\ resulting in bit set

I hope that the main point is clear: I'd like to specify the port polarity only in one place and make the code more readable and scalable.

However GCC compiler complains for it:

ipt.h:1: error: '#' is not followed by a macro parameter (column 30)

I found out that #if is not allowed within a macro definition.

How am I able to declare the macro with indicated function?


Solution

  • Try something like this:

    #define SETBIT(ADDRESS,BIT,NEG) \
      if (NEG)                      \
        (ADDRESS &= ~(1<<BIT));     \
      else                          \
        (ADDRESS |= (1<<BIT));