Preprocessor equality test, is this standard?

后端 未结 5 1926
死守一世寂寞
死守一世寂寞 2021-02-05 11:27

I had envisaged one of these in the project preferences

  • TESTING = HOST
  • TESTING = TARGET
相关标签:
5条回答
  • 2021-02-05 11:47

    I had the same problem. It used to be the compiler would error if the #if parameter was not defined which is what I wanted. I learned the hard way this is no longer the case. The solution I came up with is as follows:

    #define BUILDOPT 3
    
    #if 3/BUILDOPT == 1
        <compile>
    #endif
    

    If BUILDOPT is not defined you get a compile error for divide by 0. If BUILDOPT != 3 && > 0 the #if fails.

    0 讨论(0)
  • 2021-02-05 11:49

    My final implementation is to set BUILDOPT to 1 to enable the code, > 1 to disable. Then the #if becomes #if 1/BUILDOPT==1.

    0 讨论(0)
  • 2021-02-05 11:56
    #if TESTING==HOST
    

    If TESTING is not defined, then

    it is equivalent to:

    #if 0==HOST
    

    From the C Standard:

    (C99, 6.10.1p4) "After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0""

    0 讨论(0)
  • 2021-02-05 11:59

    And note that you can do this:

    #ifndef TESTING
        ...
    #elif TESTING == HOST
        ...
    #elif TESTING == TARGET
        ...
    #else
        #error "Unexpected value of TESTING."
    #endif
    

    Also:

    #if defined(TESTING) && TESTING == HOST
        ...
    #endif
    

    If you want to collapse the tests. The parenthesis are optional (#if defined TESTING is valid) but I think it's clearer to include them, especially when you start adding additional logic.

    0 讨论(0)
  • 2021-02-05 12:06

    The original C preprocessors required explicit #ifdef validation before using a symbol. It is a relatively recent innovation (perhaps driven by scripting languages like Javascript) to assume that undefined symbols have a default value.

    Why don't you always insure the symbol is defined?:

    #ifndef TESTING
     #define TESTING  (default value)
    #endif
    
    #if TESTING==HOST
      ...
    #elif TESTING==TARGET
     ...
    #else
     ...
    #endif
    

    Alternative, maybe force a selection?:

    #ifndef TESTING
     #error You must define a value for TESTING
    #endif
    
    0 讨论(0)
提交回复
热议问题