Chapter 4: Writing Rules 25
$(wildcard *.c)
We can change the list of C source files into a list of object files by replacing the ‘.c’
suffix with ‘.o’ in the result, like this:
$(patsubst %.c,%.o,$(wildcard *.c))
(Here we have used another function, patsubst. See Section 8.2 [Functions for String
Substitution and Analysis], page 84.)
Thus, a makefile to compile all C source files in the directory and then link them together
could be written as follows:
objects := $(patsubst %.c,%.o,$(wildcard *.c))
foo : $(objects)
cc -o foo $(objects)
(This takes advantage of the implicit rule for compiling C programs, so there is no need to
write explicit rules for compiling the files. See Section 6.2 [The Two Flavors of Variables],
page 60, for an explanation of ‘:=’, which is a variant of ‘=’.)
4.4 Searching Directories for Prerequisites
For large systems, it is often desirable to put sources in a separate directory from the
binaries. The directory search features of make facilitate this by searching several directories
automatically to find a prerequisite. When you redistribute the files among directories, you
do not need to change the individual rules, just the search paths.
4.4.1 VPATH: Search Path for All Prerequisites
The value of the make variable VPATH specifies a list of directories that make should search.
Most often, the directories are expected to contain prerequisite files that are not in the
current directory; however, make uses VPATH as a search list for both prerequisites and
targets of rules.
Thus, if a file that is listed as a target or prerequisite does not exist in the current
directory, make searches the directories listed in VPATH for a file with that name. If a file is
found in one of them, that file may become the prerequisite (see below). Rules may then
specify the names of files in the prerequisite list as if they all existed in the current directory.
See Section 4.4.4 [Writing Recipes with Directory Search], page 27.
In the VPATH variable, directory names are separated by colons or blanks. The order in
which directories are listed is the order followed by make in its search. (On MS-DOS and
MS-Windows, semi-colons are used as separators of directory names in VPATH, since the
colon can be used in the pathname itself, after the drive letter.)
For example,
VPATH = src:../headers
specifies a path containing two directories, src and ../headers, which make searches in
that order.
With this value of VPATH, the following rule,
foo.o : foo.c
is interpreted as if it were written like this:
Comentarios a estos manuales