As our programs get more complicated, we’ll want to store the various parts of the program in separate files. For example, we might store the functions we wrote for the exercises in § 6.1 (p. 205) in one file and store code that uses these functions in other source files. To allow programs to be written in logical parts, C++ supports what is commonly known as separate compilation. Separate compilation lets us split our programs into several files, each of which can be compiled independently.
As an example, assume that the definition of our fact
function is in a file named fact.cc
and its declaration is in a header file named Chapter6.h
. Our fact.cc
file, like any file that uses these functions, will include the Chapter6.h
header. We’ll store a main
function that calls fact
in a second file named factMain.cc
. To produce an executable file, we must tell the compiler where to find all of the code we use. We might compile these files as follows:
$ CC factMain.cc fact.cc # generates factMain.exe or a.out
$ CC factMain.cc fact.cc -o main # generates main or main.exe
Here CC
is the name of our compiler, $
is our system prompt, and #
begins a command-line comment. We can now run the executable file, which will run our main
function.
If we have changed only one of our source files, we’d like to recompile only the file that actually changed. Most compilers provide a way to separately compile each file. This process usually yields a file with the .obj
(Windows) or .o
(UNIX) file extension, indicating that the file contains object code.
The compiler lets us link object files together to form an executable. On the system we use, we would separately compile our program as follows:
$ CC -c factMain.cc # generates factMain.o
$ CC -c fact.cc # generates fact.o
$ CC factMain.o fact.o # generates factMain.exe or a.out
$ CC factMain.o fact.o -o main # generates main or main.exe
You’ll need to check with your compiler’s user’s guide to understand how to compile and execute programs made up of multiple source files.