C++ Macro to conditionally compile code?

前端 未结 2 1792
别那么骄傲
别那么骄傲 2021-01-20 01:07

I want to compile code conditionally based on a macro. Basically I have a macro that looks like (Simplified from the real version):

#if DEBUG
    #define STA         


        
相关标签:
2条回答
  • 2021-01-20 01:56

    Would:

    #if DEBUG
        #define START_BLOCK( x ) if(DebugVar(#x) \
            { char debugBuf[8192];
        #define END_BLOCK( ) printf("%s\n", debugBuf); }
    #else
        #define START_BLOCK( x ) {
        #define END_BLOCK( ) }
    #endif
    

    do?

    0 讨论(0)
  • 2021-01-20 02:00

    So you want conditional blocks with their own scope?

    Here's a quite readable solution that relies on the compiler to optimize it away:

    #define DEBUG 1
    
    if (DEBUG) {
        // ...
    }
    

    And here is one that is preprocessor-only:

    #define DEBUG 1
    
    #ifdef DEBUG
        #define IFDEBUG(x) {x}
    #else
        #define IFDEBUG(x)
    #endif
    
    IFDEBUG(
        // ...
    )
    

    Or manually:

    #define DEBUG 1
    
    #ifdef DEBUG
    {
        // ...
    }
    #endif
    
    0 讨论(0)
提交回复
热议问题