Chapter 4: Writing Rules 39
main.o : main.c defs.h
Thus you no longer have to write all those rules yourself. The compiler will do it for you.
Note that such a rule constitutes mentioning main.o in a makefile, so it can never be
considered an intermediate file by implicit rule search. This means that make won’t ever
remove the file after using it; see Section 10.4 [Chains of Implicit Rules], page 117.
With old make programs, it was traditional practice to use this compiler feature to
generate prerequisites on demand with a command like ‘make depend’. That command
would create a file depend containing all the automatically-generated prerequisites; then
the makefile could use include to read them in (see Section 3.3 [Include], page 13).
In GNU make, the feature of remaking makefiles makes this practice obsolete—you need
never tell make explicitly to regenerate the prerequisites, because it always regenerates any
makefile that is out of date. See Section 3.5 [Remaking Makefiles], page 14.
The practice we recommend for automatic prerequisite generation is to have one makefile
corresponding to each source file. For each source file name.c there is a makefile name.d
which lists what files the object file name.o depends on. That way only the source files that
have changed need to be rescanned to produce the new prerequisites.
Here is the pattern rule to generate a file of prerequisites (i.e., a makefile) called name.d
from a C source file called name.c:
%.d: %.c
@set -e; rm -f $@; \
$(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
sed ’s,\($*\)\.o[ :]*,\1.o $@ : ,g’ < $@.$$$$ > $@; \
rm -f $@.$$$$
See Section 10.5 [Pattern Rules], page 118, for information on defining pattern rules. The
‘-e’ flag to the shell causes it to exit immediately if the $(CC) command (or any other
command) fails (exits with a nonzero status).
With the GNU C compiler, you may wish to use the ‘-MM’ flag instead of ‘-M’. This omits
prerequisites on system header files. See Section “Options Controlling the Preprocessor” in
Using GNU CC, for details.
The purpose of the sed command is to translate (for example):
main.o : main.c defs.h
into:
main.o main.d : main.c defs.h
This makes each ‘.d’ file depend on all the source and header files that the corresponding
‘.o’ file depends on. make then knows it must regenerate the prerequisites whenever any of
the source or header files changes.
Once you’ve defined the rule to remake the ‘.d’ files, you then use the include directive
to read them all in. See Section 3.3 [Include], page 13. For example:
sources = foo.c bar.c
include $(sources:.c=.d)
(This example uses a substitution variable reference to translate the list of source files ‘foo.c
bar.c’ into a list of prerequisite makefiles, ‘foo.d bar.d’. See Section 6.3.1 [Substitution
Refs], page 62, for full information on substitution references.) Since the ‘.d’ files are
Comentários a estes Manuais