我怎么能中止一个make/makefile执行基于一个makefile的变量没有被设置/值?

我想出了这个,但只有在调用者没有显式运行目标(即只运行make)时才有效。

ifeq ($(MY_FLAG),)
abort:   ## This MUST be the first target :( ugly
    @echo Variable MY_FLAG not set && false
endif

all:
    @echo MY_FLAG=$(MY_FLAG)

我认为这样的东西会是一个好主意,但在make的手册中没有找到任何东西:

ifndef MY_FLAG
.ABORT
endif

当前回答

另一个选择:

MY_FLAG = $(error Please set this flag)

尝试在任何地方使用此变量都会导致错误,除非从命令行覆盖它。

要接受环境变量,使用?=:

MY_FLAG ?= $(error Please set this flag)

其他回答

使用shell错误处理未设置变量(注意双$):

$ cat Makefile
foo:
        echo "something is set to $${something:?}"

$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127


$ make foo something=x
echo "something is set to ${something:?}"
something is set to x

如果需要自定义错误消息,请将其添加在?:

$ cat Makefile
hello:
        echo "hello $${name:?please tell me who you are via \$$name}"

$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127

$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus

你可以使用IF来测试:

check:
        @[ "${var}" ] || ( echo ">> var is not set"; exit 1 )

结果:

$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1

使用shell函数测试:

foo:
    test $(something)

用法:

$ make foo
test 
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x

另一个选择:

MY_FLAG = $(error Please set this flag)

尝试在任何地方使用此变量都会导致错误,除非从命令行覆盖它。

要接受环境变量,使用?=:

MY_FLAG ?= $(error Please set this flag)

为了简单和简洁:

$ cat Makefile
check-%:
        @: $(if $(value $*),,$(error $* is undefined))

bar:| check-foo
        echo "foo is $$foo"

输出:

$ make bar
Makefile:2: *** foo is undefined. Stop.
$ make bar foo="something"
echo "foo is $$foo"
foo is something