Separate Compilation
Our program in
stock5.more.c
now consists of main() and two functions, stock_price() and data_ok().
The code implementing it
is beginning to get quite large.
Often, for convenience of the programmer, we like to keep the size of
the code files small (about a page or so of code) so we can see
most of it on the screen when we edit it.
To be able to do this, we often break the code up into individual files,
and can compile them separately and link them together.
There are several advantages of this:
-
The code is easier to work with and understand in smaller chunks.
-
We further hide details of how functions work when all
we are concerned about is what they do.
-
We can group related functions together into "modules".
-
We can possibly reuse functions in a module in another program
simply by linking its object code.
-
As programs get larger and therefore take longer to compile,
we can speed up the edit-compile-test loop by only recompiling those
modules we have changed.
To break up the stock program, we will use four files:
-
stock6.c -
-
A file containing just main() - often called the driver program.
-
stock_utils.c -
-
A file containing the utility functions we have written to handle
some of the details.
-
stock_utils.h -
-
A
header
file containing the protptypes for the utility
functions.
-
tfdef.h -
-
Another
header file
(which can be quite useful in many programs)
containing the macro definitions for TRUE and FALSE.
Compiling it all together
We can use the cc command to compile and link the modules of the program
as follows:
cc stock6.c stock_utils.c
and we see
ee150:wiliki:14> cc stock6.c stock_utils.c
stock6.c:
stock_utils.c:
ee150:wiliki:15> ls
a.out* stock3.c stock4_eof.dat stock_report
stock0.c stock4.count.c stock4_spv.dat stock_utils.c
stock1.c stock4.eof.c stock5.c stock_utils.h
stock1.debug.c stock4.eof2.c stock5.more.c stock_utils.o
stock1.fixed.c stock4.spv.c stock6.c tfdef.h
stock2.c stock4_count.dat stock6.o
ee150:wiliki:16>
Notice:
- We DO NOT compile the .h header files. These are "included"
when we compile the .c files.
-
The .o files produced by the compiler remain in the directory.