【问题标题】:Elegant way to remove target file if a Make rule fails如果 Make 规则失败,删除目标文件的优雅方法
【发布时间】:2017-02-17 05:06:50
【问题描述】:

我的 Makefile 中有一条大致如下所示的规则:

target_file: src_file
        some_tool src_file > target_file

(当然,实际上我使用的是$@$<,但是对于这个问题,我更喜欢更明确的风格。)

问题在于 target_file 总是由带有新时间戳的 shell 创建,即使 some_tool 失败。在这种情况下,存在一个空的target_file,即使我修复了底层问题,它也不会被重建,直到我手动删除target_file 或触摸src_file

另外,some_tool 仅写入标准输出,因此我无法通过更简洁的方法(例如 some_tool ... -o target_file)来解决此问题。

我目前的做法是删除

target_file: src_file
        some_tool src_file > target_file || rm -f target_file

但是,这样做的缺点是Make 不会注意到some_tool 失败,因为在这种情况下rm 会接管并返回退出代码 0(成功)。

另一种方法可能是:

target_file: src_file
        some_tool src_file > target_file.tmp
        mv target_file.tmp target_file

但是这种代码很乏味,失败时会留下一个烦人的文件target_file.tmp

有没有更优雅的方法来解决这个问题?

【问题讨论】:

    标签: shell makefile stdout gnu-make redirectstandardoutput


    【解决方案1】:

    你可以使用special target.DELETE_ON_ERROR

    如果 .DELETE_ON_ERROR 在 makefile 中的任何位置被提及为目标,则如果规则的目标已更改并且其配方以非零退出状态退出,则 make 将删除规则的目标,就像它收到信号时所做的那样。

    只需要一行:

    .DELETE_ON_ERROR:
    

    所有失败的规则都将被删除。

    【讨论】:

    • 谢谢!这应该是 make 中的默认行为。
    猜你喜欢
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多