Compiling and running C++ programs

C++ was developed by Bjarne Stroustrup,

http://www.research.att.com/~bs/

from the C language. Other languages, like Java and C# are also based on the C syntax.

Command line

This bit should be ignored by those who are frightened of computers, instead go straight to Xcode or DevC++.

The old way of compiling and running programs was from a command line. This is easy to do in Unix, Linux and Macintosh OS X, but probably quite difficult under Windows, but see

http://www.mingw.org/

http://msdn.microsoft.com/en-us/library/x2khzsa1(VS.71).aspx

The following applies to the GNU g++ compiler on UNIX, Linux, and Macintosh. If you are on a Windows machine you can access the University of Bath Unix machines by following

http://www.bath.ac.uk/bucs/tools/unix/accessingunix/

If you have a Macintosh use Terminal.app which is in the Utilities folder of the Applications folder.

On Linux use Applications > Accessories > Terminal

Unix commands are in

http://www.bath.ac.uk/bucs/tools/unix/basicunixcommands/

Whatever system you are using, download

http://staff.bath.ac.uk/abscjkw/ComputerPrograms/C++programs/HelloWorld.cpp

or type

#include <iostream>

#include <fstream>

#include <cmath>

#include <cstdlib>

using namespace std;

 

int main (void)

{

         cout << "Hello, World!\n";

         cout << "Press ENTER to continue... ";

         cin.get();

         return 0;

}

into your text editor and save it as HelloWorld.cpp

Then using the cd command go to the directory (folder) where you have put HelloWorld.cpp and type

g++ HelloWorld.cpp -o Hello

and press ÔreturnÕ. The word after the –o is the name of the Unix Executable. If you just type

g++ HelloWorld.cpp

the Executable will be called a.out

To run the program type

./Hello

note that there is no space between ./and Hello.

Xcode or DevC++

Most people use an integrated development environment (IDE) such as Xcode (comes with the operating system on the Developer Tools CD) on Macintosh or MicrosoftÕs Visual Studio,

http://www.microsoft.com/express/vc/

which is free to download.

However, Dev C++ is probably easier for beginners and is a much smaller download, see

http://staff.bath.ac.uk/abscjkw/ComputerPrograms/DevCpp/Downloading%20Dev%20C++.htm

In general you have to create a project before compiling and running a C++ program. You will have to create something with a name like ÔC++ Command Line UtilityÕ or ÔC++ ToolÕ.

Dev C++ has the advantage that you do not need a project to run a Command Line Utility. Simply open the HelloWorld.cpp in DevC++ and go to Execute > Compile and Run.

Using Xcode on the Macintosh you can either copy and paste from HelloWorld.cpp to Main.cpp or add HelloWorld.cpp to the project and remove Main.cpp.