System-6
Compiling and Running Programs


Compilation

People do not write programs directly in machine language. Instead, they write in a much more readable form and rely on a piece of software called a compiler to translate to machine language. We will use a compiler that translates from C++ to machine language. In general, a compiler translates a source language, such as C++, into a target language, such as machine language.


Compiling a C++ program using g++

Use g++ to compile a C++ program. Command

  g++ -Wall -W -o name prog.cpp
translates prog.cpp from C++ to machine language, creating executable program called name. Option -Wall requests all normal warnings. Option -W requests a few more that are useful. Option -o gives the name that you want the executable file to have. For example,
  g++ -Wall -W -o hailstone hailstone.cpp 
compiles hailstone.cpp and calls the executable file hailstone. (In Linux, executable files normally have no extension, unlike Windows, where executable files normally have extension .exe.)


Running your program

To run file hailstone, use command

  ./hailstone

A program normally reads from the standard input (the keyboard, by default) and writes to the standard output (the terminal by default).

You can redirect the standard input or the standard output (or both) so that they are attached to files. Command

  ./hailstone <data1.txt
runs hailstone, but it reads from file data1.txt instead of from the keyboard. Command
  ./hailstone <data1.txt >out.txt
additionally causes the output from hailstone to go into file out.txt.


Using make

The make utility makes it easy to compile software. Each assignment comes with a file called Makefile. It contains instructions for make that tell it how to build a particular piece of software. The instructions consist of a sequence of targets, dependencies and commands.

Linux command

  make tgt
tells make to build target tgt, according to the instructions in Makefile. Linux command
  make
tells make to make the first target in Makefile.


Stopping a rogue program

If your program goes into an infinite loop, you will need to stop it. Type control-C. That will usually stop it. If that does not work, see killing a process.


More information

See

Exercises

  1. What does a compiler do? Answer

  2. How can you compile assn1.cpp and create an executable file called assn1, with commonly used warning requested? Answer

  3. Suppose that assn1 is an executable file in the current directory. How can you run assn1? Answer

  4. How can you stop a running program? Answer