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

后端 未结 14 2201
心在旅途
心在旅途 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:04

    I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:

    #include 
    
    void XTrace0(LPCTSTR lpszText)
    {
       ::OutputDebugString(lpszText);
    }
    
    void XTrace(LPCTSTR lpszFormat, ...)
    {
        va_list args;
        va_start(args, lpszFormat);
        int nBuf;
        TCHAR szBuffer[512]; // get rid of this hard-coded buffer
        nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
        ::OutputDebugString(szBuffer);
        va_end(args);
    }
    

    Then a typical #ifdef switch:

    #ifdef _DEBUG
    #define XTRACE XTrace
    #else
    #define XTRACE
    #endif
    

    Well that can be cleaned up quite a bit but it's the basic idea.

提交回复
热议问题