Documenting Makefile targets

Posted 2022-02-01

Inspired by this post (Autodocumenting Makefiles) on Hacker News. This approach only requires sed. That can be a good thing or a bad thing; sed is pretty widely available, but its availability isn’t guaranteed, and flags can vary between implementations.

There is a Make-native way to do this, which is more robust. I like this approach because it’s concise, but it’s not that much more concise. There’s a tradeoff to be made for sure.

$ make
bar:  Do the bar
foo:  Do the foo
help:  Display this help message

$ make help
bar:  Do the bar
foo:  Do the foo
help:  Display this help message

See this Stack Overflow post on printing capture groups with sed for more info about the sed call.

The regular expression, piece by piece:

Note that sed has slightly different regex syntax.