Makefile- 如何在创建其他目标的目标中定义变量?

Makefile- How to define variables in a target that creates other targets?

我不完全理解如何使用特定于目标的变量来充当目标本身,它们有自己的依赖项和配方。

有效但不使用目标特定变量的 Makefile 示例:

VAR=progName
ATARGET: $(VAR)
    @echo Do actions for $@ based on the completed target $(VAR)
$(VAR):
    @echo Do actions on $@

make ATARGET

Do actions on progName

Do actions for ATARGET based on the completed target progName

Makefile 在尝试使用特定于目标的变量时不起作用(注意执行 make 时缺少 "Do actions on progName"):

ATARGET:VAR=progName
ATARGET: $(VAR)
    @echo Do actions for $@ based on the completed target $(VAR)
$(VAR):
    @echo Do actions on $@

make ATARGET

Do actions for ATARGET based on the completed target progName

所需的 Makefile 行为:

ATARGET:VAR=progName
ATARGET: $(VAR)
    @echo Do actions for $@ based on the completed target $(VAR)

BTARGET:VAR=otherProgName
BTARGET: $(VAR)
    @echo Do actions for $@ based on the completed target $(VAR)

$(VAR):
    @echo Do actions on $@

make ATARGET

Do actions on progName

Do actions for ATARGET based on the completed target progName

make BTARGET

Do actions on otherProgName

Do actions for BTARGET based on the completed target otherProgName

这些是简单的 Makefile 来说明问题 - 实际的 makefile 有几个目标,具体取决于 VAR 的值。

PGM = $(VAR)_test.exe;
LIB = lib$(VAR).a;
LIBLINKNAME = $(VAR);

您不能根据正在构建的目标更改 make 变量的值;他们在这之前就被处理了。但是,您可以拥有多个目标的规则,并使用它们产生您想要的行为。例如:

VAR = progName otherProgName

ATARGET: progName
    echo Do actions for $@ based on the completed target $<

BTARGET: otherProgName
    echo Do actions for $@ based on the completed target $<

$(VAR):
    echo Do actions on $@

VAR 现在不再是一个好听的名字了(也许叫它 LIST 或别的什么更好)。这样,相同的配方适用于 progNameotherProgName 目标,生成哪一个取决于您正在构建的目标的先决条件。

结合字符串处理函数,这适用于更复杂的用例。例如,您可以使用

# pattern substitution: append _test.exe to all entries in VAR
PGM = $(VAR:%=%_test.exe)

$(PGM):
    recipe for individual *_test.exe programs here.

您可能也非常static pattern rules感兴趣。