Skip to content

Commit

Permalink
Attach to the console on Windows
Browse files Browse the repository at this point in the history
This makes `std::cout` working again after switching to a GUI
application in prefix-dev#2067. It still
does not open a console when launched from the Windows Explorer, but
when launched from a terminal, it will now print to the terminal again,
as before.
  • Loading branch information
certik committed Sep 17, 2024
1 parent dc9b79e commit f5929dd
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions examples/cpp-sdl/src/main.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
#include <iostream>
#include <SDL.h>
#ifdef _WIN32
# include <windows.h>
#endif

int main( int argc, char* args[] ) {
#ifdef _WIN32
// Attach to the parent console if running from a console
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
// Redirect stdout to the console
FILE* fp;
freopen_s(&fp, "CONOUT$", "w", stdout);
}
#endif

std::cout << "Starting..." << std::endl;

// Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
Expand Down Expand Up @@ -78,5 +91,12 @@ int main( int argc, char* args[] ) {
SDL_DestroyWindow(window);
SDL_Quit();

std::cout << "End." << std::endl;

#ifdef _WIN32
// Detach from the console
FreeConsole();
#endif

return 0;
}

0 comments on commit f5929dd

Please sign in to comment.