Programming in C

(Barry) #1
Dividing Your Program into Multiple Files 335

the resulting object code into .objfiles instead of .ofiles.) Typically, these intermediate
object files are automatically deleted after the compilation process ends. Some C compil-
ers (and, historically, the standard Unix C compiler) keep these object files around and
do not delete them when you compile more than one file at a time.This fact can be
used to your advantage for recompiling a program after making a change to only one or
several of your modules. So in the previous example, because mod1.candmain.chad no
compiler errors, the corresponding .ofiles—mod1.oand main.o—would still be around
after the gcccommand completed. Replacing the cfrom the filename mod.cwith an o
tells the C compiler to use the object file that was produced the last time mod.cwas
compiled. So, the following command line could be used with a compiler (in this case,
cc) that does not delete the object code files:


$ cc mod1.o mod2.c main.o –o dbtest


So, not only do you not have to reedit mod1.cand main.cif no errors are discovered by
the compiler, but you also don’t have to recompile them.
If your compiler automatically deletes the intermediate .ofiles, you can still take
advantage of performing incremental compilations by compiling each module separately
and using the –ccommand-line option.This option tells the compiler not to link your
file (that is, not to try to produce an executable) and to retain the intermediate object
file that it creates. So, typing


$ gcc –c mod2.c


compiles the file mod2.c, placing the resulting executable in the file mod2.o.
So, in general, you can use the following sequence to compile your three-module
program dbtestusing the incremental compilation technique:


$ gcc –c mod1.c Compile mod1.c => mod1.o
$ gcc –c mod2.c Compile mod2.c => mod2.o
$ gcc –c main.c Compile main.c => main.o
$ gcc mod1.o mod2.o mod3.o –o dbtest Create executable


The three modules are compiled separately.The previous output shows no errors were
detected by the compiler. If any were, the file could be edited and incrementally recom-
piled.The last line that reads


$ gcc mod1.o mod2.o mod3.o


lists only object files and no source files. In this case, the object files are just linked
together to produce the executable output file dbtest.
If you extend the preceding examples to programs that consist of many modules, you
can see how this mechanism of separate compilations can enable you to develop large
programs more efficiently. For example, the commands


$ gcc –c legal.c Compile legal.c, placing output in legal.o
$ gcc legal.o makemove.o exec.o enumerator.o evaluator.o display.o –o superchess


could be used to compile a program consisting of six modules, in which only the mod-
ule legal.cneeds to be recompiled.

Free download pdf