Debug output on Windows

On Windows you don't usually run anything from a console window. Even if you did printf/cout will not normally appear unless the application is a console application.

The following code can be used to out put to the Visual Studio debug console window.

It implements a variable argument list similar to printf.

#include <cstdarg>
#include <mutex>

std::mutex outputLock_;

void DebugMessage(const char * format, ...)
{
    char buffer[1024];
    va_list marker;
    va_start(markerformat);
    vsnprintf(buffersizeof(buffer), formatmarker);
    buffer[sizeof(buffer) - 1] = '\0';
 
    std::lock_guard<std::mutex> guard(outputLock_);
    OutputDebugStringA(buffer);
    va_end(marker);
}

A number of points to note:
  • It is thread safe but the output may be scrambled.
  • Limited buffer size, though this is safe.
  • Only supports code page output.
  • If you replace OutputDebugStringA with printf/cout/cerr the method becomes more portable.

Comments