Programming Utilities Guide

Pattern-Replacement Macro References

A pattern-replacement macro reference is similar in form and function to a suffix replacement reference. You can use a pattern-replacement reference to add or alter a prefix, suffix, or both, to matching words in the value of a macro.


Note -

As with pattern-matching rules, pattern-replacement macro references are not available in earlier versions of make.


A pattern-replacement reference takes the form:

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

where p is the existing prefix to replace (if any), s is the existing suffix to replace (if any), np and ns are the new prefix and new suffix, and % is a wild card. The pattern replacement is applied to all words in the value that match `p%s. For instance:

SOURCES= old_main.c old_data.c moon 
OBJECTS= $(SOURCES:old_%.c=new_%.o) 
all: 
        	@echo $(OBJECTS)

produces:

$ make 
new_main.o new_data.o moon

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

...
OBJECTS= $(SOURCES:old_%.c=%/%.o)

would produce:

main/main.o data/data.o moon

Note, however, that pattern-replacement macro references should not appear in the dependency line of the target entry for a pattern-matching rule. This produces a conflict, since make cannot tell whether the wild card applies to the macro, or to the target (or dependency) itself. With the makefile:

OBJECT= .o 

x: 
x.Z: 
        	@echo correct 
%: %$(OBJECT:%o=%Z)

it seems as if make should attempt to build x from x.Z. However, the pattern-matching rule is not recognized; make cannot determine which of the % characters in the dependency line to use in the pattern-matching rule.