PAYATHON 2026

Makefile 中当前目录工具作为依赖后如何执行

技术问小赵

结论:在 recipe 中显式写出 $(srcdir)/tool.sed 来执行工具,不要用 $^ 直接执行。srcdir=. 时,命令是 ./tool.sed input >output,路径里有 /,shell 会直接按路径执行,不会去查 PATH;srcdir=../../src 时,命令是 ../../src/tool.sed input >output,同样成立。这样既不用把 . 加入 PATH,也不用在 Makefile 里前置 sed -f。

原因

GNU make 处理依赖列表和自动变量 $^、$< 时,可能把 ./tool.sed 规范化成 tool.sed。recipe 里的 $^ 展开后就变成 tool.sed input。shell 看到命令名里没有 /,会按 PATH 查找;而 . 通常不在 PATH 中,执行就会失败。shebang #! /usr/bin/sed -nf 只决定脚本被找到后怎么解释,解决不了 shell 查找命令的问题。

推荐写法

可以把工具路径定义成变量,依赖列表照常写全,然后在 recipe 里显式调用这个变量:

TOOL = $(srcdir)/tool.sed
INPUT = input

output: $(TOOL) $(INPUT)
	"$(TOOL)" "$(INPUT)" >$@

当 srcdir=. 时,recipe 展开为 "./tool.sed" "input" >output;当 srcdir=../../src 时,展开为 "../../src/tool.sed" "input" >output。两种情况下路径都带 /,shell 会直接执行。这里的 $(TOOL) 是在 recipe 中展开的,不会被 make 规范化成 tool.sed。

想保留自动变量时

如果仍想用 $< 取第一个依赖,可以在 POSIX shell 里判断路径中是否包含 /:

output: $(srcdir)/tool.sed input
	@tool='$<'; case "$$tool" in */*) ;; *) tool="./$$tool" ;; esac; "$$tool" input >$@

$< 是第一个依赖,所以依赖顺序要把工具放在 input 前面。路径含 / 时,包括 ../../src/tool.sed 和绝对路径,直接使用;不含 / 就补上 ./。这段 recipe 没有用 GNU make 的 $(if) 或 $(filter),可移植性更好。

注意事项

  • 不要把 . 加到全局 PATH 里,比如 PATH := .:$(PATH)。这样会改变所有 recipe 的命令查找顺序,当前目录里如果有同名程序,很容易被误执行。
  • 不要无条件写成 ./$<。srcdir 可能是绝对路径,前面加 ./ 反而会破坏它。显式写 $(srcdir)/tool.sed,或者用上面的 case 判断,更稳妥。
  • 确认 tool.sed 有可执行权限,shebang 也正确。#! /usr/bin/sed -nf 会保留 -n 参数,直接执行脚本即可。
  • 如果路径里可能有空格,recipe 中要给变量加引号;依赖列表里的文件名也要按 make 规则转义。
  • 如果用的不是 GNU make,尽量采用显式变量或 POSIX shell 判断,少用 GNU make 专有函数。

备注:内容仅供参考。