Makefiles:在同一隐含目标中的两个不同先决条件之间交替

Makefiles: Alternate between two different prerequisites in the same implicit goal

我正在编写我的第一个 makefile,但遇到了一个问题。

我有一堆先决条件,其中第一个是需要处于特殊位置的模板。我要这样做:

target : req1 req2 req3
    command $(filter-out $<,$^) $@ --template=$<

问题是,有时我需要将该模板切换为另一个模板,同时保留其他先决条件,因此

# Changing just the first prerequisite
target : req1b req2 req3
    command $(filter-out $<,$^) $@ --template=$<

我正在寻找一种方法来使用我现在的目标来实现这一点,而不是编写一个特别明确的目标,也许用参数或类似的东西调用 make,但我也知道关于完成它的 makefile 很少。

一般的想法是您将要使用一个变量,如何设置该变量由您决定。一种方法是通过命令行传递变量。您的 Makefile 看起来像:

target : $(REQ_ONE) req2 req3
    command $(filter-out $<,$^) $@ --template=$<

然后执行 make target REQ_ONE=reg1make target REQ_ONE=reg1b

如果您有一个希望使用的首选默认值(比如 req1)并且您希望在极少数情况下使用替代方案,您可以使用上一个示例的修改形式。

# only set if the variable doesn't exist
REQ_ONE ?= req1

target : $(REQ_ONE) req2 req3
    command $(filter-out $<,$^) $@ --template=$<

最后,此方法的一个变体是让您的 Makefile 调用 make 进行变量赋值:

# only set if the variable doesn't exist
REQ_ONE ?= req1

target2:
    $(MAKE) target REQ_ONE=req1b

target : $(REQ_ONE) req2 req3
    command $(filter-out $<,$^) $@ --template=$<

另一种解决方案是使用此 SO post on target specific variables as a prerequisites 中演示的二次扩展。