Skip to content

Instantly share code, notes, and snippets.

@kosh04
Last active May 2, 2022 14:49
Show Gist options
  • Select an option

  • Save kosh04/eaf7ed31782dc9e513c8 to your computer and use it in GitHub Desktop.

Select an option

Save kosh04/eaf7ed31782dc9e513c8 to your computer and use it in GitHub Desktop.
WinMainなプログラムでもコンソール出力がしたい
// attach-console.c
// Usage1: > cl attach-console.c & attach-console.exe
// Usage2: $ gcc attach-console.c && ./a.exe
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
// エクスプローラから起動した場合は新規にコンソールを割り当てる
AllocConsole();
}
freopen("CONIN$", "r", stdin); // "CONIN$", "CONOUT$", "CON" の違いがよく分かっていない
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
printf("HELLO WORLD!\n");
FreeConsole();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment