How do I print to the debug output window in a Win32 app?
If you want to print decimal variables:
wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print
You can use OutputDebugString
. OutputDebugString
is a macro that depending on your build options either maps to OutputDebugStringA(char const*)
or OutputDebugStringW(wchar_t const*)
. In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L
prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T
macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
To print to the real
console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE
. The extra console window is annoying, but for debugging purposes it's very valuable.
OutputDebugString
prints to the debugger output when running inside the debugger.
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
- In "linker->System->SubSystem" the value "Console (/SUBSYSTEM:CONSOLE)"
- In "C/C++->Preprocessor->Preprocessor Definitions" add the "_CONSOLE" define
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen
is deprecated and may be unsafe. Use freopen_s
instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);