Makefile 函数中变量未生效问题小记

文章目录

问题

遇到了一个奇怪的问题,特此记录。

变量在 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 string hello/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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值