Ifdef 条件意外行为

Ifdef conditional unexpected behavior

我有一个包含如下命令的 Makefile:

#Makefile
    hello:
        echo 'hello'
        echo $(TAG)
        ifdef TAG
              $(warning MYWARNING)
        else
              $(error MYERROR)
        endif

我这样使用它:

# make TAG='1.0' hello

我希望该命令执行 echo 'hello',然后 echo $(TAG) 和 $(warning MYWARNING) 但我得到:

Makefile:17: MYWARNING
Makefile:19: *** MYERROR.  Stop.

怎么了?

让我们尝试一些更简单的情况(*)。

hello:
    echo hello
    $(error MYERROR)

这会产生:

Makefile:3: *** MYERROR.  Stop.

请注意 error 阻挡了 echo,即使它在后面。

现在让我们尝试一些愚蠢的事情:

hello:
    ifdef TAG

结果是:

ifdef TAG
make: ifdef: No such file or directory

“ifdef TAG”,解释为shell命令,没有意义。它被解释为 shell 命令,因为它在配方中并且前面有一个 TAB。

现在让我们把它们结合起来:

hello:
    ifdef TAG
    $(error MYERROR)

结果是 Makefile:3: *** MYERROR. Stop. 所以 error 掩盖了 ifdef... 不正确的事实。

我们想要 shell 条件,还是 Make 条件?如果我们想要 Make 对其进行操作(使用 errorwarning),那么它必须是一个 Make 条件,所以我们不能在它之前使用 TAB:

hello:
ifdef TAG
    $(warning MYWARNING)
else
    $(error MYERROR)
endif

这按预期工作。

(*) 因为你应该在发帖之前尝试过。