生成文件导出变量,用于触发先决条件



这是我的makefile段代码,我想更好地理解为什么它不工作:

.PHONY: main_rule
main_rule: export MAIN=1
main_rule: main_prereq
... some stuff here ...

.PHONY: main_prereq
main_prereq: $(if $(filter 1,$(MAIN)),true_cond,false_cond)
..... other stuff here ...
.PHONY: true_cond
true_cond: 
..... other stuff here ...
.PHONY: false_cond
false_cond: 
..... other stuff here ...

我的问题在"导出MAIN=1"我认为main_preeq能够执行true_cond,而不是将其导出到先决条件列表。

我使用导出的原因是因为main_preeq可以被其他规则调用,所以我需要一些东西来区分执行(true_cond仅用于main,否则false_cond用于所有其他规则)。

即使你对我的问题有更好的解决方案,我也恳请你帮助我理解为什么它不起作用(我想我没有抓住所有的makefile哲学)。

从GNUmake手册中引用:

规则总是以相同的方式展开,无论形式如何:

immediate : immediate ; deferred
deferred

第二个immediate指的是先决条件列表——这个列表在第一阶段评估(第二阶段是"执行")。对于正常规则,$(MAIN)的值不会在make评估filter表达式时设置——目标特定变量只在第二阶段设置。在您的情况下,SECONDEXPANSION应该可以做到:

.PHONY: main_rule
main_rule: export MAIN=1
main_rule: main_prereq
... some stuff here ...
.SECONDEXPANSION:  # from here on all rules will be expanded a second time
# all $-denoted values will be evaluated the first time,
# so we need to quote $$ everything we want to have evaluated 
# only the second way round
.PHONY: main_prereq
main_prereq: $$(if $$(filter 1,$$(MAIN)),true_cond,false_cond)
..... other stuff here ...
.PHONY: true_cond
true_cond: 
..... other stuff here ...
.PHONY: false_cond
false_cond: 
..... other stuff here ...