We can automate this process by writing a Makefile
for our program.
A sample Makefile
is shown in Figure 7.
Figure 7: An example Makefile.
This Makefile
is very simple.
Three rules are shown for the files that must be generated.
Each file name at the left hand side of a colon is called a target;
after the colon the target's dependencies are specified.
Make rebuilds a target whenever it does not exist or when it is
out-of-date with respect to one of its dependencies.
For example, after we rewrote our my_math.c
implementation,
my_math.o
and facfib
are out-of-date with respect to
my_math.c
.
Rebuilding is done according to the commands that are specified on the
subsequent lines.
Note that a command must start with a TAB character, and not with a SPACE.
The order in which entries appear is unimportant, except that make
builds the first target (in this case facfib
) if no target is
specified on the command line.
So always write the rule that builds the executable of your program as
first rule. Multiple commands may span consecutive lines; the command line is
terminated by a blank line. A line that is terminated by a backslash ('
')
character is continued on the next line.
Dependencies are checked recursively.
A dependency might be target of another entry.
So is my_math.o
both dependency in the first rule and target in the
second rule.
Before make decides whether or not to update facfib
, it
checks if it is necessary to update my_math.o
and main.o
.
After entering the Makefile
, we can run make to generate
an executable named facfib
.
Unless we tell make to be silent, make tells what it is doing.
Let us see what happens if we simply type ``make
'' (after deleting
my_math.o
, main.o
and facfib
).
make make: `facfib' is up to date. make gcc -c -O2 -ansi -pedantic -Wall my_math.c gcc my_math.o main.o
The first time we run make, it builds the targets as specified by
the rules.
The second time, make responds that facfib
is up to date.
If we touch (i.e. modify) my_math.c
and rerun make, it decides to
rebuild the targets my_math.o
and facfib
.