Programming Utilities Guide

Pattern-Replacement Macro References

As with suffix rules and pattern-matching rules, pattern-replacement macro references have been added to provide a more general method for altering the values of words in a specific macro reference than that already provided by suffix replacement in macro references. A pattern-replacement macro reference takes the form:

$ (macro :p %s =np %ns )

where p is an existing prefix (if any), s is an existing suffix (if any), np and ns are the new prefix and suffix, and % is a wild card character matching a string of zero or more characters within a word.

The prefix and suffix replacements are applied to all words in the macro value that match the existing pattern. Among other things, this feature is useful for prefixing the name of a subdirectory to each item in a list of files. For instance, the following makefile:

SOURCES= x.c y.c z.c 
SUBFILES.o= $(SOURCES:%.c=subdir/%.o) 

all: 
        	@echo $(SUBFILES.o)

produces:

$ make 
subdir/x.o subdir/y.o subdir/z.o

You can use any number of % wild cards in the right-hand (replacement) side of the = sign, as needed. The following replacement:

...
NEW_OBJS= $(SOURCES:%.c=%/%.o)

would produce:

...
x/x.o y/y.o z/z.o

Pattern-replacement macro references should not appear on the dependency line of a pattern-matching rule's target entry. This produces unexpected results. With the makefile:

OBJECT= .o 

x: 
%: %.$(OBJECT:%o=%Z) 
        	cp $< $@

it appears that make should attempt to build a target named x from a file named x.Z. However, the pattern-matching rule is not recognized; make cannot determine which of the % characters in the dependency line apply to the pattern-matching rule and that apply to the macro reference.

Consequently, the target entry for x.Z is never reached. To avoid problems like this, you can use an intermediate macro on another line:

OBJECT= .o 
ZMAC= $(OBJECT:%o=%Z) 

x: 
%: %$(ZMAC) 
        	cp $< $@