$@ 如何在 make 条件下工作?

Jay*_*Fix 3 conditional makefile

我正在使用 GNU Make 3.80。在我的 Makefile 中,我使用自动变量 $@ 来引用当前目标。

    @echo current target is ... [$@]
ifeq ($@,sms)
    @echo yep, they are equal
else
    @echo no, they are not equal
endif
Run Code Online (Sandbox Code Playgroud)

似乎 $@ 扩展为 sms,如下面的输出所示。

输出是:

current target is ... [sms]
no, they are not equal
Run Code Online (Sandbox Code Playgroud)

我的问题:由于 $@(显然)扩展为 sms,不应该执行 ifeq 条件的“true”分支(结果输出应该是 yep,它们是相等的)?[我不知道为什么输出不是,它们不相等。]

ssm*_*mir 5

来自GNU Make 手册

10.5.3 自动变量... 认识到自动变量值的可用范围有限,这一点非常重要:它们仅在配方中具有值。... GNU make 有一个特殊功能,二次扩展(参见二次扩展),它允许在先决条件列表中使用自动变量值。

也就是说,$@只能在包含构建目标的命令的部分中使用,并且有一些限制,在先决条件列表中使用。

但是,您可以使用 shell 命令在用于构建目标的命令列表中实现条件:

    @echo current target is ... [$@]
    if [[ "$@" == "sms" ]]; then \
         echo yep, they are equal; \
    else \
         echo no, they are not equal; \
    fi
Run Code Online (Sandbox Code Playgroud)

此外,如果您想检查在命令行上指定了哪些目标,请使用 MAKECMDGOALS 变量。