Automation and Make

Pattern rules

Learning Objectives

  • Write Make pattern rules.
  • Use the Make wild-card % in targets and dependencies.
  • Use the Make special variable $* in actions.
  • Avoid using the Make wild-card in rules.

Our Makefile still has repeated content. The rules for each .dat file are identical apart from the text and data file names. We can replace these rules with a single pattern rule which can be used to build any .dat file from a .txt file in books/:

%.dat : books/%.txt wordcount.py
        python wordcount.py $< $*.dat

% is a Make wild-card. $* is a special variable which gets replaced by the stem with which the rule matched.

If we re-run Make,

$ make clean
$ make dats

then we get:

python wordcount.py books/isles.txt isles.dat
python wordcount.py books/abyss.txt abyss.dat
python wordcount.py books/last.txt last.dat

Our Makefile is now much shorter and cleaner:

# Count words.
.PHONY : dats
dats : isles.dat abyss.dat last.dat

%.dat : books/%.txt wordcount.py
    python wordcount.py $< $*.dat

# Generate archive file.
analysis.tar.gz : *.dat wordcount.py
    tar -czf $@ $^

.PHONY : clean
clean :
        rm -f *.dat
        rm -f analysis.tar.gz