Self-Documenting Makefiles

Overview

Teaching: 10 min
Exercises: 0 min

Questions

How should I document a Makefile?

Objectives

Write self-documenting Makefiles with built-in help.

Many bash commands, and programs that people have written that can be
run from within bash, support a --help flag to display more
information on how to use the commands or programs. In this spirit, it
can be useful, both for ourselves and for others, to provide a help
target in our Makefiles. This can provide a summary of the names of
the key targets and what they do, so we don’t need to look at the
Makefile itself unless we want to. For our Makefile, running a help
target might print:

But every time we add or remove a rule, or change the description of a
rule, we would have to update this rule too. It would be better if we
could keep the descriptions of the rules by the rules themselves and
extract these descriptions automatically.

The bash shell can help us here. It provides a command called
sed which stands for ‘stream editor’. sed reads in some
text, does some filtering, and writes out the filtered text.

So, we could write comments for our rules, and mark them up in a way
which sed can detect. Since Make uses # for comments, we can use
## for comments that describe what a rule does and that we want
sed to detect. For example:

If we add, change or remove a target or rule, we now only need to
remember to add, update or remove a comment next to the rule. So long
as we respect our convention of using ## for such comments, then our
help rule will take care of detecting these comments and printing
them for us.