manpagez: man pages & more
info make
Home | html | info | man

4.14 Generating Prerequisites Automatically

In the makefile for a program, many of the rules you need to write often say only that some object file depends on some header file. For example, if ‘main.c’ uses ‘defs.h’ via an #include, you would write:

main.o: defs.h

You need this rule so that make knows that it must remake ‘main.o’ whenever ‘defs.h’ changes. You can see that for a large program you would have to write dozens of such rules in your makefile. And, you must always be very careful to update the makefile every time you add or remove an #include.


cc -M main.c

generates the output:

main.o : main.c defs.h


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 Chains of Implicit Rules.

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 Including Other Makefiles).


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 $@; \
         rm -f $@.$$$$




main.o : main.c defs.h


main.o main.d : main.c defs.h


Once you’ve defined the rule to remake the ‘.d’ files, you then use the include directive to read them all in. See section Including Other Makefiles. 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 Substitution References, for full information on substitution references.) Since the ‘.d’ files are makefiles like any others, make will remake them as necessary with no further work from you. See section How Makefiles Are Remade.




© 2000-2018
Individual documents may contain additional copyright information.