A GNU Make Tutorial

An Example

Version 3 -- Pattern Rules

Even using variables, version 2 of the test suite contains 40 pairs of rules, all with a very similar structure. Using pattern rules, this can be reduced to just two rules.

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. For instance, the target 't1.%.o' matches any file beginning with 't1.' and ending with '.o' and having at least one character in between. The part that matches the '%' is called the stem.

'%' in a dependency of a pattern rules stands for the same stem that was matched by the '%' in the target. In order for the pattern rule to apply, its target pattern must match the file name under consideration, and its dependency patterns must name files that exist or can be made. The files become dependencies of the target.

Thus the rule for assembling a dlx program becomes

# Assemble the program.
t1.%.o:	t1.%.dlx dlxasm
In order for this to work, however, there must be a mechanism to also generalize the commands invoked by the rule. Automatic variables provide this mechanism. Automatic variables are set by make after the rule has been matched using a specific stem. For example, the full rule for assembling a DLX program is
# Assemble the program.
t1.%.o:	t1.%.dlx dlxasm
	$(dlxasm) -o t1.$*.o < t1.$*.s
Here $* is an automatic variable which is set to the stem matched in the pattern rule. That is, when the target is t1.Addi.o, $* will be set to 'Addi'. If another test requires the program t1.Jump.o, then $* will be set to 'Jump'. When these variables are expanded in the command invoking dlxasm, the appropriate program will be assembled.

Here is a table of the most useful automatic variables:

The stem with which an implicit rule matches. If the target is 'dir/a.foo.b' and the target pattern is 'a.%.b' then the stem is 'dir/foo'. The stem is useful for constructing names of related files.

The file name of the target of the rule.

The name of the first dependency.

The names of all the dependencies that are newer than the target, with spaces between them.

The names of all the dependencies, with spaces between them.

[Previous] [Next] [Tutorial Index] [GNU Make]

Copyright 1996 by Byron Weber Becker