【问题标题】:makefile: fail on single make target if variable emptymakefile:如果变量为空,则在单个 make 目标上失败
【发布时间】:2018-08-16 00:25:50
【问题描述】:

我是构建 Makefile 的新手,我正在尝试确定如果变量为空,构建目标将如何失败。我希望能够将变量作为环境变量或作为 make 参数传递。

假设我有一个这样的 makefile:

VER ?=

step0:
    echo "step0 should work"

step1: 
    echo "step1 should enforce variable"
    ifeq($(VER), "")
    $(error VER is not set)
    endif 
    echo "Success: Value of Ver ${VER}"

step2:
    echo "step2 should work"

我希望能够运行以下测试用例:

VER="foo" make step1  
# should result in printing the "Success:" line

export VER=foo
make step1  
# should result in printing the "Success:" line

make step1 VER=foo  
# should result in printing the "Success:" line

make step1  
# should result in printing "VER is not set"

但是,当我使用上述任何方法运行 make step 时,我总是会收到 VER is not set 错误。

简而言之,我如何测试特定 make 目标中的变量并在未设置时以错误消息响应? (但其他 make 目标不会关心变量是否设置)

【问题讨论】:

    标签: bash makefile build scripting gnu-make


    【解决方案1】:

    有几点:

    首先,您必须将 Make 命令和 shell 命令整齐地分开。这个:

    ifeq ($(A),$(B))
    ...
    endif
    

    Make 语法。如果您将 ifeq (...) 传递给 shell,您可能会遇到麻烦。 makefile 配方中的命令是 shell 命令,要传递给 shell。要在规则中间使用 Make ifeq 条件,请执行以下操作:

    step1:
        some command
    ifeq ($(A),$(B))
        another command
    endif
        yet another command
    

    注意ifeqendif之前没有TAB;这些不是要传递给 shell 的命令,它们是供 Make 使用的。

    第二,这个:

    ifeq(...)
    

    应该是这样的:

    ifeq (...)
    

    空间很重要(至少在我的 Make 版本中)。

    第三,这个:

    ifeq ($(VER), "")
    

    应该是这样的:

    ifeq ($(VER),)
    

    除非你真的打算让变量包含字符串'""'。

    (您本可以自己发现最后一个,单独使用ifeq;始终单独测试新工具。)

    在这些更改之后,makefile 对我有用。如果它不适合你,请告诉我,我们会敲定它。

    【讨论】:

    • 感谢您帮我解决这个问题。它有助于知道 make 语法的缩进独立于目标块。有了你的建议,我能够让它工作。再次感谢。
    猜你喜欢
    • 2023-02-18
    • 1970-01-01
    • 2023-03-25
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多