Is there a way to both check a macro is defined and it equals a certain value at the same time

前端 未结 6 1411
别跟我提以往
别跟我提以往 2020-12-15 17:39

I regularly use object-like preprocessor macros as boolean flags in C code to turn on and off sections of code.

For example

#define          


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 18:19

    as far as I can tell, there is no preprocessor option to throw errors/warnings if a macro is not defined when used inside a #if statement.

    It can't be an error because the C standard specifies that behavior is legal. From section 6.10.1/3 of ISO C99 standard:

    After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number 0....

    As Jim Balter notes in the comment below, though, some compilers (such as gcc) can issue warnings about it. However, since the behavior of substituting 0 for unrecognized preprocessor tokens is legal (and in many cases desirable), I'd expect that enabling such warnings in practice would generate a significant amount of noise.

    There's no way to do exactly what you want. If you want to generate a compilation failure if the macro is not defined, you'll have to do it explicitly

    #if !defined DEBUG_PRINT
    #error DEBUG_PRINT is not defined.
    #endif
    

    for each source file that cares. Alternatively, you could convert your macro to a function-like macro and avoid using #if. For example, you could define a DEBUG_PRINT macro that expands to a printf call for debug builds but expands to nothing for non-debug builds. Any file that neglects to include the header defining the macro then would fail to compile.


    Edit:

    Regarding desirability, I have seen numerous times where code uses:

    #if ENABLE_SOME_CODE
    ...
    #endif
    

    instead of:

    #ifdef ENABLE_SOME_CODE
    ...
    #endif
    

    so that #define ENABLE_SOME_CODE 0 disables the code rather than enables it.

提交回复
热议问题