Jordan M. Baron Jordan M. Baron - 4 months ago 23
C Question

C executable returns immediately

I installed the GCC compiler to write some C code, but when I navigate to the directory, and use the command

gcc -o helloworld helloworld.c
It makes an executable on my desktop like normal, but when I run it, the executable closes immediately

I don't think that the code is the problem, but it's a possibility.

#include <stdio.h>

int main()
{
printf("Hello world\n");
return 0;
}

Answer

You have missed this line getchar() in your code.

#include <stdio.h>

int main()
{
  printf("Hello world\n");
  getchar();
  return 0;
}

Note: Though, this is not the fix as Keith Thompson explains. Instead, this is a way where you can force the program from exiting until it waits for a keypress before the console window exits.


Another way (without using getchar())

Open the Command Prompt (cmd.exe), and navigate to the program's directory and run your program from there. You'll find that the window doesn't disappears anymore, rather it stays open.

Comments