MC logo
Multi-File Programs
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Point Hdr File] [Point Impl File] [Point User File] [Point Class Hdr File] [Point Class Impl File] [Point Class User File] [C++ Integer Stack ADT] [C++ Integer Stack Implementation] [C++ Integer Stack Driver]
Reading: Ch. 23, which covers more than is discussed in this section.

C and C++ do not require a program to be broken into multiple files, but it is often helpful to do so. These files may be compiled separately, which gives the main reasons to use them:

A multi-file program contains several code files (.c or .cpp) which contain the various executable code, and header (.h) files which are used to relate them. The code files use the #include directive to read the headers. The code files are compiled and combined by a link step. The header files are not compiled, except indirectly when the #include directive is performed.

To compile a multi-file C program, the compilation process is broken up into two steps. (The compiling system may handle this automatically, so it won't be obvious, but it gets done somewhere.)

  1. Each .c or .cpp file is translated independently. The compiler obeys the #include directives in each file, so the .h files are read at this time. The .c files are coordinated by including a common .h file. Each file x.c produces a an object file called x.o or x.obj
  2. The object files are combined into an executable without consulting any of the source code files. This is called the link step.
For instance, the C++ stack example given later is broken into three files, istack2.h, istack2.cc and istackuse2.cc. Each of the .cc files contains an #include "istack2.h". The steps to compile the program would be:
g++ -c istack2.cc

This produces the file istack2.o (or istack2.obj on Windows), in the process reading the istack2.h file because istack2.cc includes it. The -c on the command tells the compiler that we're going to do the link part later, and it should produce the object file and stop. (By default, it performs the link process on the single file along with the standard libraries and produces an executable.)

g++ -c istackuse2.cc

This produces the istackuse2.o or .obj file. The istack2.h file is read again during the compile because istackuse2.cc also includes it.

g++ -o istackuse2 istackuse2.o istack2.o

This combines the object files into an executable called stackuse. The file names will usually differ on Windows, though the same operation is performed.