1. 条件判断语句
- makefile 中支持条件判断语句
- 可以根据条件的值来决定 make 的执行
- 可以比较两个不同变量或者变量和常量的值
注:条件判断语句只能用于控制 make 实际执行的语句;但是,不能控制规则中命令的执行过程。
2. 语法说明
- 常用形式
ifxxx (arg1,arg2)
- 其它
ifxxx "arg1" "arg2"
ifxxx 'arg1' 'arg2'
ifxxx "arg1" 'arg2'
ifxxx 'arg1' "arg2"
.PHONY: test
var1 := A
var2 := $(var1)
var3 :=
test:
ifeq ($(var1),$(var2)) # ifeq else endif前不能有tab键
@echo "var1 == var2"
else
@echo "var1 != var2"
endif
.PHONY : test
var1 := A
var2 := $(var1)
var3 := # 定义一个没有值的变量
test:
ifeq ($(var1),$(var2)) # 前面使用空格
@echo "var1 == var2" # 前面使用tab
else
@echo "var1 != var2"
endif
ifneq ($(var2),)
@echo "var2 is NOT empty"
else
@echo "var2 is empty"
endif
ifdef var2
@echo "var2 is NOT empty"
else
@echo "var2 is empty"
endif
ifndef var3
@echo "var3 is empty"
else
@echo "var3 is NOT empty"
endif
3. 经验
- 条件判断语句之前可以有空格,但不能有
tab 字符('\t')
- 在条件语句中不要使用自动变量(
$@
,$^
,$<
) - 一条完整的条件语句必须位于同一个 Makefile 中
- 条件判断类似于 C 语言中的宏,预处理阶段有效,执行阶段无效
- make 在加载 makefile 时:
- 首先计算表达式的值(赋值方式不同,计算方式不同)
- 根据判断语句的表达式决定执行的内容
.PHONY : test
var1 :=
var2 := $(var1)
var3 =
var4 = $(var3) # 递归赋值,无法在预处理时判断是否被定义,所以var4打印出已经被定义
test:
ifdef var1
@echo "var1 is defined"
else
@echo "var1 is not defined"
endif
ifdef var2
@echo "var2 is defined"
else
@echo "var2 is not defined"
endif
ifdef var3
@echo "var3 is defined"
else
@echo "var3 is not defined"
endif
ifdef var4
@echo "var4 is defined"
else
@echo "var4 is not defined"
endif
.PHONY : test
var1 :=
var2 := $(var1)
var3 =
var4 = $(var3) # 递归赋值,无法在预处理时判断是否被定义,所以var4打印出已经被定义
var3 = 3 # make在解析makefile时,完全可以判断出var3是否有值,而不用等到执行期间
test:
ifdef var1
@echo "var1 is defined"
else
@echo "var1 is not defined"
endif
ifdef var2
@echo "var2 is defined"
else
@echo "var2 is not defined"
endif
ifdef var3
@echo "var3 is defined"
else
@echo "var3 is not defined"
endif
ifdef var4
@echo "var4 is defined"
else
@echo "var4 is not defined"
endif