CHAPTER 2

image

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 a terminal window as long as you have a C++ compiler.1 For example, on a Linux machine you can use the GNU C++ compiler, which is available on virtually all Unix systems, including Linux and the BSD family, as part of the GNU Compiler Collection (GCC). This compiler can also be installed on Windows by downloading MinGW or on Mac as part of the Xcode development environment.

To use the GNU compiler you type its name "g++" in a terminal window and give it the input and output filenames as arguments. It then produces an executable file, which when run gives the same result as one compiled under Windows in Visual Studio.

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

Comments

Comments are used to insert notes into the source code. They have no effect on the end program and are meant only to enhance the readability of the code, both for you and for other developers. C++ has two kinds of comment notations - single-line and multi-line. The single-line comment starts with // and extends to the end of the line.

// single-line comment

The multi-line comment may span more than one line and is delimited by /* and */.

/* multi-line comment */

Keep in mind that whitespace characters – such as comments, spaces, and tabs – are generally ignored by the compiler. This allows you a lot of freedom in how to format your code.

________________

1http://www.stroustrup.com/compilers.html

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.79.121