"#if defined" clause intersected

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • moshe koren

    "#if defined" clause intersected

    Hi, i'd like to have code blocks A and B if AB is defined
    and B and C block if BC is defined.
    is the writing below correct ?


    Code:
    void func(...)
    { 
    #if defined AB
    A
    #if defined BC
    B
    #endif
    C
    #endif

    thanks,
    Last edited by Markus; Nov 7 '10, 10:04 PM.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The usual practice is to use the macro to provide different code so when you run the program you can see what happened.

    Either that, or you need to intercept the translation unit file that is being sent to the compiler.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Since B is always included it should not be inside any preprocessor conditional. Use the symbols to control the inclusion of A and C

      Code:
      void func(...)
      {
      #if defined AB
      A
      #endif
      B
      #if defined BC
      C
      #endif

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Hi, i'd like to have code blocks A and B if AB is defined and B and C block if BC is defined.
        Please clarify your requirements. There are four possibilities: neither are defined, both are defined, only AB defined, only BC defined. My guess is that you desire the following behavior:
        Block: both, neither, only AB, only BC
        A: yes, no, yes, no
        B: yes, no, yes, yes
        C: yes, no, no, yes
        Is this what you want?

        You stated the problem in terms of desired behavior for each control variable. It would be clearer to state the inclusion rules for each block:
        Block A is present if AB is defined.
        Block B is present if either AB or BC are defined.
        Block C is present if BC is defined.
        (If that is indeed the behavior you want.)

        Thus:
        Code:
        #if defined(AB)
        A
        #endif
        #if defined(AB) || defined(BC)
        B
        #endif
        #if defined(BC)
        C
        #endif
        I elected to use #if syntax instead of #ifdef syntax in order to support the logical expression for block B. I then used the same syntax for blocks A and C for consistency. In my opinion the inclusion logic is harder to understand if you nest the preprocessor statements.

        Suppose you only want to include block C if BC is defined, but AB isn't. Then you would do this:
        Code:
        #if !defined(AB) && defined(BC)
        C
        #endif

        Comment

        Working...