0

Redirect all stdout/stderr to console

If your Windows executable is using /SUBSYSTEM:WINDOWS rather than /SUBSYSTEM:CONSOLE, something you will have noticed your output messages to stdout (printf, std::cout etc) will be missing.

You can easily solve this however by spawning your own Windows console window and redirecting stdout to your new console.

The code below will redirect all stdout & stderr messages to a new console window:

if (AllocConsole())
{
	AttachConsole(GetCurrentProcessId());
	HANDLE hConOut
		= CreateFileA("CONOUT$", GENERIC_WRITE, 
			FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
		
	SetStdHandle(STD_OUTPUT_HANDLE, hConOut);
	SetStdHandle(STD_ERROR_HANDLE, hConOut);

	//Ensures FILE* object remapped to new console window
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);

	//Allows use of _write(1,...) & _write(2,...) to be redirected
	freopen("CONOUT$", "w", _fdopen(1, "w"));
	freopen("CONOUT$", "w", _fdopen(2, "w"));
}