Sunday, September 9, 2012

Makefiles: pattern-specific example


Pattern-specific macros work in a similar manner to target-specific macros, but instead of being defined for a target they are defined for a pattern and then will be applied to all targets that match that pattern.

The below example shows a pattern-specific macro.  The last line says that for any target that begins with f followed by anything (that's the % wildcard) VAR has the value starts with f.

.PHONY: all foo bar baz

VAR = global scope

all: foo bar
   @echo In $@ VAR is $(VAR)

foo:
   @echo In $@ VAR is $(VAR)

bar: VAR = local scope
bar: baz
   @echo In $@ VAR is $(VAR)

baz:
   @echo In $@ VAR is $(VAR)

f%: VAR = starts with f

Now if you run make you get the following output:

In foo VAR is starts with f
In baz VAR is local scope
In bar VAR is local scope
In all VAR is global scope

This is the same as above except that in the rule for foo the value of VAR has been set to starts with f by the pattern-specific definition.

It's worth noting that this is unrelated to normal GNU Make pattern rules.  The pattern-specific macro definition can be used to change the value of a macro in a normal rule (as above).  It can also be used with a pattern rule.

For example, you could change the value of DEBUG to 1 within all %.o files (that could be built using the standard %.o: %.c pattern rule) by writing:

%.o: DEBUG = 1

No comments:

Post a Comment