Search code examples
cc-preprocessorconditional-compilation

How to void if/else preprocessor macro with another define?


Suppose I have a c header file test.h

// test.h
#ifdef A
    int a;
#else
    int b;
#endif

Now suppose I want to build my code in such a way that both a and b are defined if B is defined. Is there a smarter way rather than:

// test.h
#ifndef B
#ifdef A
    int a;
#else
    int b;
#endif
#else
    int a;
    int b;
#endif

?

Thanks


Solution

  • Just treat the two variables separately and determine the logic for when each should be defined:

    #if defined(A) || defined(B)
        int a;
    #endif
    #if !defined(A) || defined(B)
        int b;
    #endif