WSU logo


College of Engineering & CS
Wright State University
Dayton, Ohio 45435-0001

CEG 333: Introduction to Unix

Prabhaker Mateti

The Unix Programming Environment


Although there are IDEs available for UNIX, in the interests of time and learning the underlying machinery, we will go to the basics.

This course does not have a goal of adding anything to your knowledge of C++. But it does describe how to edit, compile, link, execute and debug C++ programs. This knowledge will be used in higher-level CS courses, in which programs are required to work on UNIX.

Compilation: An Overview

A simple compilation has five main steps:

  1. User invokes a compiler frontend, such as g++, cc, and gcc. This is the only command the user must type; all others are run automatically by the compiler.
  2. Preprocessor: cpp. Evaluates all the #-directives and strips out comments.
  3. Compiler: cc1plus or cc1. Translates source code into low-level assembly language.
  4. Assembler: as. Translate the compiler output into an object file that the computer understands.
  5. Linker: ld. Combines object files into the final compiled executable program or library.

g++

G++ is the C++ interface of the GNU Compiler Collection (GCC). That means it's an interface that knows how to invoke whichever combination of compilers, assemblers, and linkers are needed for a particular source file. The set of programs needed to compile code is called the toolchain. On Linux, a typical toolchain consists of compilers from GCC and an assembler and linker from the GNU Binutils.

Syntax: g++ [-c] [-o FILENAME] SOURCEFILE.cpp

-c produce object files instead of linking
-g Compile in debugging symbols
-o FILENAME Name the output file FILENAME
-Wall Show extra warnings

Note: Although the g++ command is what a user types to compile C++ programs, the g++ program is not itself a compiler.

Source code is typically split among several files, which are compiled individually into .o object files. The object files are then linked into final program. That way, if one part of the code is changed, the programmer doesn't need to wait for the whole thing to be recompiled—only that file. This is called separate compilation. To make g++ stop before linking and thus produce object files, use the -c option.

On many modern Unix systems, object files are in the ELF (Executable and Linking Format). This is a very flexible standard which has replaced most of the various different executable file formats used by Unix developers.

Traditionally, the output file of UNIX compilers is named a.out unless the user specifies another name. To give an alternate filename, use the -o option.

Example: Compiling the program myprog from C++ source in two files:

      $ g++ -c file1.cpp -o file1.o
      $ g++ -c file2.cpp -o file2.o
      $ g++ file1.o file2.o -o myprog