TL;DR:使用误差函数:
ifndef MY_FLAG
$(error MY_FLAG is not set)
endif
注意,行不能缩进。更准确地说,这些行之前不能有制表符。
通用解决方案
如果你要测试很多变量,为它定义一个辅助函数是值得的:
# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
# 1. Variable name(s) to test.
# 2. (optional) Error message to print.
check_defined = \
$(strip $(foreach 1,$1, \
$(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
$(if $(value $1),, \
$(error Undefined $1$(if $2, ($2))))
下面是如何使用它:
$(call check_defined, MY_FLAG)
$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
LIB_INCLUDE_DIR \
LIB_SOURCE_DIR, \
library path)
这将输出如下错误:
Makefile:17: *** Undefined OUT_DIR (build directory). Stop.
注:
真正的检查是这样的:
$(if $(value $1),,$(error ...))
这反映了ifndef条件的行为,因此定义为空值的变量也被认为是“未定义的”。但这只适用于简单变量和显式空递归变量:
# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)
# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)
正如@VictorSergienko在评论中所建议的,可能需要稍微不同的行为:
$(if $(value $1)测试值是否为非空。如果变量定义为空值,有时是可以的。我将使用$(if $(过滤器未定义,$(起源$1))…
And:
此外,如果它是一个目录,并且在运行检查时它必须存在,我将使用$(if $(通配符$1))。而是另一个函数。
有针对性的检查
还可以扩展解决方案,以便只有在调用某个目标时才需要变量。
$(调用check_defined,…
只需将支票移动到食谱中:
foo :
@:$(call check_defined, BAR, baz value)
前导@符号关闭命令回显,:是实际的命令,一个shell no-op存根。
显示目标名称
check_defined函数也可以改进为输出目标名称(通过$@变量提供):
check_defined = \
$(strip $(foreach 1,$1, \
$(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
$(if $(value $1),, \
$(error Undefined $1$(if $2, ($2))$(if $(value @), \
required by target `$@')))
因此,现在一个失败的检查会产生一个格式化的输出:
Makefile:7: *** Undefined BAR (baz value) required by target `foo'. Stop.
check-defined-MY_FLAG特殊目标
就我个人而言,我会使用上面简单直接的解决方案。然而,例如,这个答案建议使用一个特殊的目标来执行实际的检查。我们可以尝试将其概括,并将目标定义为隐式模式规则:
# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
# %: The name of the variable to test.
#
check-defined-% : __check_defined_FORCE
@:$(call check_defined, $*, target-specific)
# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :
用法:
foo :|check-defined-BAR
注意,检查定义的bar被列为仅限订单(|…)的先决条件。
优点:
(可以说)一个更干净的语法
缺点:
不能指定自定义错误消息
运行make -t(参见Instead of execution Recipes)将会用大量check-defined-…文件。这是模式规则不能被声明为. phony的一个遗憾的缺点。
我相信,这些限制可以通过一些计算魔法和二次扩展技巧来克服,尽管我不确定这是否值得。