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

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

    Ah, vsprintf() was the thing I was missing. I can use this to pass the variable argument list directly to printf():

    #include <stdarg.h>
    #include <stdio.h>
    
    void DBG_PrintImpl(char * format, ...)
    {
        char buffer[256];
        va_list args;
        va_start(args, format);
        vsprintf(buffer, format, args);
        printf("%s", buffer);
        va_end(args);
    }
    

    Then wrap the whole thing in a macro.

    0 讨论(0)
  • 2020-12-23 10:30

    This is a TCHAR version of user's answer, so it will work as ASCII (normal), or Unicode mode (more or less).

    #define DEBUG_OUT( fmt, ...) DEBUG_OUT_TCHAR(       \
                TEXT(##fmt), ##__VA_ARGS__ )
    #define DEBUG_OUT_TCHAR( fmt, ...)                  \
                Trace( TEXT("[DEBUG]") #fmt,            \
                ##__VA_ARGS__ )
    void Trace(LPCTSTR format, ...)
    {
        LPTSTR OutputBuf;
        OutputBuf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT,   \
                (size_t)(4096 * sizeof(TCHAR)));
        va_list args;
        va_start(args, format);
        int nBuf;
        _vstprintf_s(OutputBuf, 4095, format, args);
        ::OutputDebugString(OutputBuf);
        va_end(args);
        LocalFree(OutputBuf); // tyvm @sam shaw
    }
    

    I say, "more or less", because it won't automatically convert ASCII string arguments to WCHAR, but it should get you out of most Unicode scrapes without having to worry about wrapping the format string in TEXT() or preceding it with L.

    Largely derived from MSDN: Retrieving the Last-Error Code

    0 讨论(0)
提交回复
热议问题