Sunday, August 19, 2007

Gnu-make: pattern rule

A pattern rule contains the character `%' (exactly one of them) in the
target; otherwise, it looks exactly like an ordinary rule. The target is
a pattern for matching file names; the `%' matches any nonempty
substring, while other characters match only themselves

Here are some examples of pattern rules actually predefined in make.
First, the rule that compiles `.c' files into `.o' files:

%.o : %.c
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@

defines a rule that can make any file `x.o' from `x.c'. The command uses
the automatic variables `$@' and `$<' to substitute the names of the
target file and the source file in each case where the rule applies (see
section Automatic Variables).

Gnu-make: patsubst

is equivalent to
$(patsubst pattern,replacement,$(var))
The second shorthand simplifies one of the most common uses of patsubst:
replacing the suffix at the end of file names.
is equivalent to
$(patsubst %suffix,%replacement,$(var))
For example, you might have a list of object files:
objects = foo.o bar.o baz.o
To get the list of corresponding source files, you could simply write:
instead of using the general form:
$(patsubst %.o,%.c,$(objects))

Blog Archive