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

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

    It's a matter of style. But I recommend a more concise way of doing this:

    #ifdef USE_DEBUG
    #define debug_print printf
    #else
    #define debug_print
    #endif
    
    debug_print("i=%d\n", i);
    

    You do this once, then always use debug_print() to either print or do nothing. (Yes, this will compile in both cases.) This way, your code won't be garbled with preprocessor directives.

    If you get the warning "expression has no effect" and want to get rid of it, here's an alternative:

    void dummy(const char*, ...)
    {}
    
    #ifdef USE_DEBUG
    #define debug_print printf
    #else
    #define debug_print dummy
    #endif
    
    debug_print("i=%d\n", i);
    

提交回复
热议问题