Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/G++ hello world application issue, maybe compilation

Tags:

c++

I am trying to compile my first c++ file on windows with the g++ compiler...

My cpp file is the following -

#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World!";
  return 0;
}

I type in this on command prompt to get to the directory

cd C:\Users\Mark

Then to compile my program I do

g++ hello.cpp

It creates a file name a.exe (default) but when I click on it the command prompt quickly flashes open then it's gone.

What did I do wrong? It should say Hello World! on the prompt and stay there, right?

like image 943
Mark Lalor Avatar asked Nov 27 '25 16:11

Mark Lalor


2 Answers

What you did looks correct, but if you start the program by double clicking it in Windows, the new command prompt will be closed once it is finished. Since you already have a command prompt open for compilation, try to start the program from there, too:

g++ hello.cpp -o hello.exe
hello.exe
like image 182
ollb Avatar answered Nov 29 '25 06:11

ollb


That's just normal Windows behavior of executing a command-line file from the UI -- as soon as the program exits (immediately in your case), the prompt window closes.

Running it from the command line will keep it up. To do that, Start > Run > cmd, then cd to the directory, then type a.exe.

Alternatively, you can wait for input from the user to keep the window open. That's fine for testing, but nobody who actually executes programs from the command line would want to have to hit a key to stop a program from running, when it should exit on its own correctly.

like image 32
Mark Rushakoff Avatar answered Nov 29 '25 05:11

Mark Rushakoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!