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

后端 未结 19 865
忘了有多久
忘了有多久 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:02

    I like #define DEBUG_ENABLED (0) when you might want multiple levels of debug. For example:

    #define DEBUG_RELEASE (0)
    #define DEBUG_ERROR (1)
    #define DEBUG_WARN (2)
    #define DEBUG_MEM (3)
    #ifndef DEBUG_LEVEL
    #define DEBUG_LEVEL (DEBUG_RELEASE)
    #endif
    //...
    
    //now not only
    #if (DEBUG_LEVEL)
    //...
    #endif
    
    //but also
    #if (DEBUG_LEVEL >= DEBUG_MEM)
    LOG("malloc'd %d bytes at %s:%d\n", size, __FILE__, __LINE__);
    #endif
    

    Makes it easier to debug memory leaks, without having all those log lines in your way of debugging other things.

    Also the #ifndef around the define makes it easier to pick a specific debug level at the commandline:

    make -DDEBUG_LEVEL=2
    cmake -DDEBUG_LEVEL=2
    etc
    

    If not for this, I would give advantage to #ifdef because the compiler/make flag would be overridden by the one in the file. So you don't have to worry about changing back the header before doing the commit.

提交回复
热议问题