Using logical operators with macros
Asked Answered
C

4

11

I have a piece of code which I want to include if either of two macros are defined

#ifdef MACRO1 || MACRO2

void foo()
{


}

#endif

How do I accomplish this in C?

Conveyor answered 4/12, 2012 at 21:3 Comment(0)
P
19

Besides #ifdef, the preprocessor supports the more general #if instruction; actually, #ifdef MACRO is a shortcut for #if defined(MACRO), where defined is a "preprocessor function" that returns 1 if the macro is defined; so, you can do:

#if defined(MACRO1) || defined(MACRO2)

void foo()
{


}

#endif
Pronation answered 4/12, 2012 at 21:5 Comment(2)
What is the issue in below code? What is the alternative in case such kind of usage is incorrect? #define CUSTOM_METHOD 1 #define ARDUINO_METHOD 2 #define TIMER_DELAY_METHOD CUSTOM_METHOD #if defined (TIMER_DELAY_METHOD != CUSTOM_METHOD) || defined(TIMER_DELAY_METHOD!=ARDUINO_METHOD) #error "No timer method is defined" #endif // definedStomacher
I think I got it and following code seems to be working #define CUSTOM_METHOD 1 #define ARDUINO_METHOD 2 #define NONE 3 #define TIMER_DELAY_METHOD NONE #if (TIMER_DELAY_METHOD != CUSTOM_METHOD) && (TIMER_DELAY_METHOD != ARDUINO_METHOD) #error "No timer method is defined" #endif // definedStomacher
P
5
#if defined(MACRO1) || defined(MACRO2)
Parcheesi answered 4/12, 2012 at 21:4 Comment(0)
C
5

Here the NOT version if needed:

#if !defined(MACRO1) && !defined(MACRO2)
...
#endif
Copperhead answered 16/12, 2014 at 12:27 Comment(0)
I
0
  #if defined(Macro 1) + defined(Macro 2) == 1
  <Code>
  #endif  
Incorrupt answered 4/12, 2012 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.