如何在命令失败时中止makefile?

时间:2018-03-08 09:49:18

标签: makefile gnu-make

我想在启动编译之前检查第三方库是否可用。使用pkg-config很容易,但我想要一个比以下更好的错误消息:

pkg-config gtk+-3.0
make: *** [Makefile:17: gtk+-3.0] Error 1

在这里阅读了一些答案后,我发现了一个令人满意的代码:

gtk+-3.0:
    $(shell pkg-config $@)
    ifneq ($(.SHELLSTATUS),0)
        $(error $@ is not installed)
    endif

但错误总是被触发。

如果我将$(error)替换为echo,则会出现语法错误:

ifneq (0,0)
/bin/sh: -c: line 0: syntax error near unexpected token `0,0'
/bin/sh: -c: line 0: `ifneq (0,0)'
make: *** [Makefile:3: gtk+-3.0] Error 1

在archlinux上使用GNU Make 4.2.1。

1 个答案:

答案 0 :(得分:1)

当命令失败时,

Make 已经停止。只需写下

gtk+-3.0:
        pkg-config $@

或者为了更好地控制消息,

gtk+-3.0:
        @if pkg-config $@; then \
           printf '%s\n' "All good!"; \
        else \
           printf '%s\n' "Not installed." >&2; \
           exit 1; \
        fi

请注意, make 始终使用Bourne shell(可能是/bin/sh),因此对于简单命令不需要$(shell)。使用 make -conditionals也没有像你期望的那样完成。 GNU make 手册包含所有细节。