问题
遇到了一个奇怪的问题,特此记录。
变量在 Make 函数中似乎未生效,如下:
pwd := $$PWD
test:
echo ${subst /,//,${pwd}}
结果如下:
>>> make test
echo $PWD
/Users/zzzzls/Deskto
可以看到 subst 函数似乎完全没有任何效果!
原因
感谢 Stack overflow,原文如下:Makefile subst variable not affected?
原文回答:
You can’t combine make functions with shell variables… all make functions are expanded first, then the resulting script is passed to the shell to be run. When the shell gets the script there are no more make functions in it (and if there were, the shell wouldn’t know what to do with them!)
Your subst is running on the literal string
$x
, which has no/
so nothing to replace and results in$x
, which the shell expands to the stringhello/world
.
大意是:make 函数不能使用 shell 变量「例:$$pwd
」,make 函数运行时,shell 变量会以字面量的形式传递,以 Python 代码举例:
pwd = "/Users/zzzzls/Desktop"
# 期望代码
pwd.replace("/", "//")
# 实际执行
"pwd".replace("/", "//")
而 pwd 中并没有 /
,也就没有东西可以替换,所以 echo ${subst /,//,${pwd}}
⇒ echo $$PWD
,也就出现上文的效果了!
解决
可参考下述做法
pwd := ${shell pwd}
test:
echo ${subst /,//,$(pwd)}
>>> make test
echo //Users//zzzzls//Desktop
//Users//zzzzls//Desktop