We have a file called array.h
that exposes the interface of an
array abstract data type (ADT). We have a file called array.c
that
implements the array ADT. array.c
includes array.h
. We also
have a file main.c
that utilizes the array ADT. main.c
also
includes array.h
.
In order for the make
program to do its magic, it needs to have a
text file that describes the dependencies amongst files. This
textfile is often called the ``Makefile'', and is usually named exactly
as Makefile
. The following
is the minimal content of this Makefile:
main: main.o array.o gcc -o main main.o array.o array.o: array.c array.h gcc -c array.c main.o: main.c array.h gcc -c main.c
Each rule in a Makefile consists of two parts: a dependency and commands.
The dependency of a rule specifies the target file, and the files that
the target file relies on. In our example, ``array.o: array.c array.h
'' means that the file array.o
depends on the files array.c
and
array.h
. This also means that if any one of array.c
or
array.h
is modified, array.o
needs to be refreshed.
Technically, the filename of the lhs of the colon is called the
``target'', and all the files to the right hand side are called the
prerequisite.
The command(s) of a rule specifies how to generate the target from its
dependent files. In our example, the command ``gcc -c array.c
'' is
what we need to generate a fresh copy of array.o
. Note that
array.h
is not supplied as a parameter because it is
#include
d in the source file.
Also note that the each command of a rule must not begin in column 1 of a line. Each command must be preceded by at least one tab character. No, the space character doesn't do the trick! This part is difficult to convey in the sample Makefile code.
Once you have this simple Makefile constructed (and save it as
Makefile
), then you can invoke the make
command as follows:
make main
The make
program interprets the content of Makefile
, and
executes the necesary commands in the right order to bring the
target main
up-to-date.
The first target main
has a special meaning. It is the ``default''
target. If you only want to bring the default target up-to-date, you can
do the following instead:
make
Yep, it doesn't any easier (in terms of using make
once the Makefile
is constructed).
Now, you can edit array.h
, and then use the make
command to
recompile and relink the program the way it should be done! If you do this
manually, you may forget that both array.c
and main.c
need to be recompiled, and lead to very strange problems.
Copyright © 2006-10-08 by Tak Auyeung