How to document a makefile?

The following is a simpler solution that does not require defining user functions or aggregating help text away from the rules they document.

# This is a regular comment, that will not be displayed

## ----------------------------------------------------------------------
## This is a help comment. The purpose of this Makefile is to demonstrate
## a simple help mechanism that uses comments defined alongside the rules
## they describe without the need of additional help files or echoing of
## descriptions. Help comments are displayed in the order defined within
## the Makefile.
## ----------------------------------------------------------------------

help:     ## Show this help.
    @sed -ne '/@sed/!s/## //p' $(MAKEFILE_LIST)

build:    ## Build something.

install:  ## Install something.

deploy:   ## Deploy something.

format:   ## Help comments are display with their leading whitespace. For
          ## example, all comments in this snippet are aligned with spaces.

Running make or make help results in the following:

----------------------------------------------------------------------
This is a help comment. The purpose of this Makefile is to demonstrate
a simple help mechanism that uses comments defined alongside the rules
they describe without the need of additional help files or echoing of
descriptions. Help comments are displayed in the order defined within
the Makefile.
----------------------------------------------------------------------
help:     Show this help.
build:    Build something.
install:  Install something.
deploy:   Deploy something.
format:   Help comments are display with their leading whitespace. For
          example, all comments in this snippet are aligned with spaces.

One nice touch is to provide a phony help target that prints a summary of targets and options. From the Linux kernel Makefile:

help:
        @echo  'Cleaning targets:'
        @echo  '  clean           - Remove most generated files but keep the config and'
        @echo  '                    enough build support to build external modules'
        @echo  '  mrproper        - Remove all generated files + config + various backup files'
        @echo  '  distclean       - mrproper + remove editor backup and patch files'
        @echo  ''
        @echo  'Configuration targets:'
        @$(MAKE) -f $(srctree)/scripts/kconfig/Makefile help
        @echo  ''

It might be a bit of work to maintain the documentation this way, but I find it nicely separates what is intended for "users" versus what is intended for people maintaining the Makefile itself (inline comments).


In a makefile such as :

install: ## Do a
  @echo "foo"

start: ## Do b
  @echo "bar"

test: ## Do c
  @echo "baz"

help:
  @egrep -h '\s##\s' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m  %-30s\033[0m %s\n", $$1, $$2}'

Will output :

enter image description here