Makefile 比较字符串输入

Makefile compare string input

为了更好地理解 Makefile 中的字符串变量,我试着做了这个例子:

KEYWORD=Nothing

test:
    $(call myFunc)

define myFunc
ifeq ($(KEYWORD), "Apple")
    echo "You have found the key"
else
    echo "Try again"
endif
endef

但是当我打字时

make test KEYWORD="Fork"

它打印错误

syntax error near unexpected token `Fork,'
`ifeq (Fork, "Apple")'

我也试过了:

我 运行 没有想法,因为我不明白 Makefille / Shell 如何解释作业 KEYWORD="Fork"

谢谢

首先,$(call myfunc) 与写作 $(myfunc) 100% 相同。 make 中的 call 函数只是扩展了一个变量,其中首先绑定了一些其他局部值(参数)。如果您不提供任何局部值,那么您只是在扩展变量。

扩展变量只是将变量引用替换为它扩展到的内容。所以写:

FOO = bar
foo:
        echo $(FOO)

与写作 100% 相同:

foo:
        echo bar

所以在你的情况下,

test:
        $(call myFunc)

等同于:

test:
        $(myFunc)

等同于:

test:
        ifeq ($(KEYWORD), "Apple")
            echo "You have found the key"
        else
            echo "Try again"
        endif

这就是您获得输出的原因:这些不是有效的 shell 命令,但由于您已将变量扩展为配方的一部分,因此它们将发送到 shell作为食谱的一部分。

MadScientist 指出了问题所在。也许您正在寻找的解决方案只是更早地评估条件。例如:

KEYWORD ?= NOTHING
...
ifeq ($(KEYWORD), Apple)
define myFunc
        echo "You have found the key"
endef
else
define myFunc
        echo "Try again"
endef
endif