Multiple File Compilation

Multiple File Projects:

Most of the time, full programs are not contained in a single file.  Many small programs are easy to write in a single file, but larger programs involve separate files containing different modules. Usually, files are separated by related content.

A class module normally consists of:

Filenames:
Header files are usually in the format filename.h, and implementation files are usually in the format filename.cpp. It is a good idea to use the same base filename for corresponding header and implementation files. Example:

 circle.h    // header file for a class called Circle 
 circle.cpp  // implementation file for Circle class 
Filenames do not have to be the same as the class name, but well-chosen filenames can help identify the contents or purpose of a file.

When classes are used in a program, the main program would usually be written in a separate file.
 

Compilation

The "compilation" of a program actually consitsts of two major stages.
  1. Compile stage
  2. Linking stage

Putting together a multiple-file project

For a simple example like our Fraction example, it may be tempting to simply use the following statement inside the main.cpp file:
  #include "frac.cpp"
and then just compile the main.cpp file with a single command. This will work in this example, because it's a linear sequence of #includes -- this essentially causes the whole thing to be put together into one file as far as the compiler is concerned. This is not a good idea in the general case. Sometimes the line-up of files is not so linear. The separate ideas of compiling and linking allow these steps to be done separately and there are some good reasons and benefits:

Rule of thumb: Only #include the header files, not the .cpp files!

Visual C++

Example CS account (g++) commands for compilation and linking:

g++ -c frac.cpp                // translates frac.cpp into object code, frac.o 
g++ -c main.cpp                // translates main.cpp into object code, main.o 
g++ frac.o main.o -o sample    // links object code files into an executable called "sample" 

Building basic multiple-file projects