You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Makefile中修改变量?问题排查与解决方案

问题:Makefile中test-if步骤修改var2变量未生效

我想在Makefile的test-if步骤里把var2从'test2'改成'test3',但修改始终不生效。尝试的代码如下:

var1 = 'test1'
var2 = 'test2'

test-if:
    @echo $(var1)
    @echo $(var2)
    @if [ '$(var1)' = 'test1' ]; then\
        echo "equals";\
        export var2='test3';\
    else echo "not equals";\
    fi
    @echo $(var2)

试过去掉export直接写var2='test3',还是没用;用$(var2)='test3'则报错:/bin/sh: 3: test2=test3: not found。


原因分析
  1. Shell进程隔离:Makefile里每一行命令都会启动独立的Shell进程执行,你在if语句的Shell进程中修改的var2是Shell变量,不会影响Makefile层面的var2,后续@echo $(var2)属于另一个Shell进程,自然读不到修改后的值。
  2. 变量展开时机:$(var2)是Makefile的变量引用,会在Makefile解析阶段就被替换成原始值'test2',而非Shell运行时动态获取更新后的值。

解决方案

使用Makefile原生的条件判断ifeq,配合$(eval override)修改Makefile变量,这样修改会作用在Makefile层面,后续命令能读取到更新后的值:

var1 = test1
var2 = test2

test-if:
    @echo ${var1}
    @echo ${var2}
ifeq (test1, $(var1))
    @echo "equals"
    $(eval override var2 = 'test3')
 else 
    @echo "not equals"
endif
    @echo ${var2}

执行make test-if会输出预期结果:

test1
test2
equals
test3

内容的提问来源于stack exchange,提问作者bota4go

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:51:29