Skip to content

Instantly share code, notes, and snippets.

@pplmx
Last active September 4, 2023 02:27
Show Gist options
  • Save pplmx/11f6515fa12d7b96d856a18f6373d3f6 to your computer and use it in GitHub Desktop.
Save pplmx/11f6515fa12d7b96d856a18f6373d3f6 to your computer and use it in GitHub Desktop.
Makefile help generator
.PHONY: help
.DEFAULT_GOAL := help
# Show help
help:
@echo ""
@echo "Usage:"
@echo " make [target]"
@echo ""
@echo "Targets:"
@awk '/^[a-zA-Z\-_0-9]+:/ \
{ \
helpMessage = match(lastLine, /^# (.*)/); \
if (helpMessage) { \
helpCommand = substr($$1, 0, index($$1, ":")-1); \
helpMessage = substr(lastLine, RSTART + 2, RLENGTH); \
printf "\033[36m%-22s\033[0m %s\n", helpCommand,helpMessage; \
} \
} { lastLine = $$0 }' $(MAKEFILE_LIST)
@pplmx
Copy link
Author

pplmx commented Apr 25, 2023

When you run make help from the command line, the target performs the following actions:

  1. Prints basic usage information, such as make [target].
  2. Uses the awk command to read the Makefile and find all lines that start with a letter, number, hyphen, or underscore and end with a colon. These lines represent targets defined in the Makefile.
  3. For each target found, the awk command checks if the line above it starts with a #. If it does, it assumes that line contains help information for that target.
  4. If help information is found, it uses the printf command to print the target name and help information.

This way, you can add help information for each target in your Makefile, and then use the make help command to automatically generate a help document.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment