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

前端 未结 6 1390
别跟我提以往
别跟我提以往 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:29

    Rather than using DEBUG_PRINT directly in your source files, put this in the header file:

    #if !defined(DEBUG_PRINT)
        #error DEBUG_PRINT is not defined
    #endif
    
    #if DEBUG_PRINT
        #define PrintDebug([args]) [definition]
    #else
        #define PrintDebug
    #endif
    

    Any source file that uses PrintDebug but doesn't include the header file will fail to compile.

    If you need other code than calls to PrintDebug to be compiled based on DEBUG_PRINT, consider using Michael Burr's suggestion of using plain if rather than #if (yes, the optimizer will not generate code within a false constant test).

    Edit: And you can generalize PrintDebug above to include or exclude arbitrary code as long as you don't have commas that look like macro arguments:

    #if !defined(IF_DEBUG)
        #error IF_DEBUG is not defined
    #endif
    
    #if IF_DEBUG
        #define IfDebug(code) code
    #else
        #define IfDebug(code)
    #endif
    

    Then you can write stuff like

    IfDebug(int count1;)  // IfDebug(int count1, count2;) won't work
    IfDebug(int count2;)
    ...
    IfDebug(count1++; count2++;)
    

提交回复
热议问题