如何在项目顶层调用子目录Makefile规则且无需重复定义?
问题描述
项目结构如下:
/project | |-/pythonsrc | |- Makefile | |- ... | |-/javasrc | |- Makefile | |- ... | |- Makefile
在/project/pythonsrc/Makefile中定义了如下规则:
.PHONY: format-python-code format-python-code: black .
希望既能在/project目录下运行make format_python_code(无需重复定义规则或编写调用子规则的规则),也能在/project/pythonsrc目录下运行该规则。请问能否将子目录Makefile中的规则暴露到顶层?这是否可行?
可行方案
可以实现,核心是通过Make的include指令将子目录Makefile的规则导入顶层,同时调整命令路径适配不同运行目录:
1. 调整子目录Makefile的路径逻辑
修改/project/pythonsrc/Makefile,让格式化命令的路径基于当前Makefile所在目录,避免顶层运行时路径错误,同时添加下划线命名的规则别名:
.PHONY: format-python-code format_python_code # 获取当前Makefile所在目录的绝对路径 PYTHON_SRC_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) format-python-code: black $(PYTHON_SRC_DIR) # 添加下划线命名的别名,匹配需求中的调用方式 format_python_code: format-python-code
2. 顶层Makefile导入子规则
在/project/Makefile中添加一行导入语句:
include pythonsrc/Makefile
效果验证
- 在
/project/pythonsrc目录下运行make format-python-code或make format_python_code,都会正确格式化当前目录下的Python代码。 - 在
/project目录下运行make format_python_code,导入的规则会直接生效,命令会定位到pythonsrc目录执行格式化,无需额外定义规则。
内容的提问来源于stack exchange,提问作者Schlameel
相关产品推荐
相关产品推荐

