首页 > 解决方案 > 在 Makefile 中,使用带有子文件夹和子文件夹替换的 patsubst 和通配符

问题描述

我正在尝试使用 makefile 将一些降价文件转换为 html 文件。我试图用几行代码来完成我之前有一个很长的 python 脚本正在做的事情。

在下面的简单示例中,我想看看这段代码:

build: $(patsubst src/pages/%.md, output/%.html, $(wildcard src/pages/*.md))

%.html: %.md
    @echo $< to $@

这个输出

src/pages/index.md to output/index.html
src/pages/about.md to output/about.html
src/pages/contact.md to output/contact.html
src/page/foo/bar.md to output/foo/bar.html

相反,它说:

$ make build
make: *** No rule to make target 'output/index.html', needed by 'build'.  Stop.

我在这里遗漏了一些非常基本的东西。

标签: makefile

解决方案


考虑目标output/index.html。依赖...

%.html: %.md

将有效地扩展到...

output/index.html: output/index.md

$*等于output/index。_ 所以make寻找output/index.md但找不到它 - 因此出现错误消息。

要获得正确的模式词干($*== index),您需要将基本目录添加到模式规则中......

output/%.html: src/pages/%.md
    @echo $< to $@

编辑1:

如果您担心重复的硬编码字符串,例如output然后src/pages您总是可以将它们分配给参数......

OUTPUT_DIR := output
SOURCE_DIR := src/pages

build: $(patsubst $(SOURCE_DIR)/%.md, $(OUTPUT_DIR)/%.html, $(wildcard $(SOURCE_DIR)/*.md))


$(OUTPUT_DIR)/%.html: $(SOURCE_DIR)/%.md
    @echo $< to $@

(假设这就是您评论中“优化”的意思。)


推荐阅读