News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C++ Tutorial – 03 – Compile and Run

Visual Studio compilation

Continuing from the last chapter, the Hello World program is now complete and ready to be compiled and run. You can do this by going to the Debug menu and clicking on Start Without Debugging (Ctrl + F5). Visual Studio then compiles and runs the application which displays the text in a console window.

If you select Start Debugging (F5) from the Debug menu instead, the console window displaying Hello World will close as soon as the main function is finished. To prevent this you can add a call to the cin::get function at the end of main. This function, belonging to the console input stream, will read input from the keyboard until the return key is pressed.

#include <iostream>
using namespace std;
 
int main()
{
  cout << "Hello World";
  cin.get();
}

Console compilation

As an alternative to using an IDE you can also compile source files from the command line as long as you have a C++ compiler. For example, on a Linux machine you can use the GNU C++ compiler, which is available on virtually all Unix systems. You type the compiler name “g++” and give it the input and output filenames as arguments. It then produces an executable, which when run gives the same result as one compiled under Windows.

g++ MyApp.cpp -o MyApp.exe
./MyApp.exe
Hello World

Comments

C++ has two kinds of comment notations – single-line and multi-line. These are used to insert notes into the source code and will have no effect on the end program.

// single-line comment
 
/* multi-line
   comment */
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day