#ifdef vs #if - which is better/safer as a method for enabling/disabling compilation of particular sections of code?

后端 未结 19 780
忘了有多久
忘了有多久 2020-11-30 17:26

This may be a matter of style, but there\'s a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...

Basically, we have some de

相关标签:
19条回答
  • 2020-11-30 18:15

    #if gives you the option of setting it to 0 to turn off the functionality, while still detecting that the switch is there.
    Personally I always #define DEBUG 1 so I can catch it with either an #if or #ifdef

    0 讨论(0)
  • 2020-11-30 18:15

    The first seems clearer to me. It seems more natural make it a flag as compared to defined/not defined.

    0 讨论(0)
  • 2020-11-30 18:22

    Both are exactly equivalent. In idiomatic use, #ifdef is used just to check for definedness (and what I'd use in your example), whereas #if is used in more complex expressions, such as #if defined(A) && !defined(B).

    0 讨论(0)
  • Alternatively, you can declare a global constant, and use the C++ if, instead of the preprocessor #if. The compiler should optimize the unused branches away for you, and your code will be cleaner.

    Here is what C++ Gotchas by Stephen C. Dewhurst says about using #if's.

    0 讨论(0)
  • 2020-11-30 18:23

    There is a difference in case of different way to specify a conditional define to the driver:

    diff <( echo | g++ -DA= -dM -E - ) <( echo | g++ -DA -dM -E - )
    

    output:

    344c344
    < #define A 
    ---
    > #define A 1
    

    This means, that -DA is synonym for -DA=1 and if value is omitted, then it may lead to problems in case of #if A usage.

    0 讨论(0)
  • 2020-11-30 18:24

    I used to use #ifdef, but when I switched to Doxygen for documentation, I found that commented-out macros cannot be documented (or, at least, Doxygen produces a warning). This means I cannot document the feature-switch macros that are not currently enabled.

    Although it is possible to define the macros only for Doxygen, this means that the macros in the non-active portions of the code will be documented, too. I personally want to show the feature switches and otherwise only document what is currently selected. Furthermore, it makes the code quite messy if there are many macros that have to be defined only when Doxygen processes the file.

    Therefore, in this case, it is better to always define the macros and use #if.

    0 讨论(0)
提交回复
热议问题