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

当您在命令行中运行 make help 时,该目标会执行以下操作:

  1. 打印出基本的使用信息,例如 make [target]
  2. 使用 awk 命令读取 Makefile 文件,并查找所有以字母、数字、短划线或下划线开头且以冒号结尾的行。这些行表示 Makefile 中定义的目标。
  3. 对于每个找到的目标,awk 命令会检查该目标上方的行是否以 # 开头。如果是,则假定该行包含有关该目标的帮助信息。
  4. 如果找到帮助信息,则使用 printf 命令打印出目标名称和帮助信息。

这样,您可以在 Makefile 中为每个目标添加帮助信息,然后使用 make help 命令自动生成帮助文档。

@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