How do you create a debug only function that takes a variable argument list? Like printf()

后端 未结 14 2200
心在旅途
心在旅途 2020-12-23 09:44

I\'d like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.

<
14条回答
  •  渐次进展
    2020-12-23 10:17

    @CodingTheWheel:

    There is one slight problem with your approach. Consider a call such as

    XTRACE("x=%d", x);
    

    This works fine in the debug build, but in the release build it will expand to:

    ("x=%d", x);
    

    Which is perfectly legitimate C and will compile and usually run without side-effects but generates unnecessary code. The approach I usually use to eliminate that problem is:

    1. Make the XTrace function return an int (just return 0, the return value doesn't matter)

    2. Change the #define in the #else clause to:

      0 && XTrace
      

    Now the release version will expand to:

    0 && XTrace("x=%d", x);
    

    and any decent optimizer will throw away the whole thing since short-circuit evaluation would have prevented anything after the && from ever being executed.

    Of course, just as I wrote that last sentence, I realized that perhaps the original form might be optimized away too and in the case of side effects, such as function calls passed as parameters to XTrace, it might be a better solution since it will make sure that debug and release versions will behave the same.

提交回复
热议问题