Makefile函数条件语句未执行,参数获取异常求助
Makefile函数
set_target_dts错误排查与修复 核心问题
你在define函数中直接使用Makefile顶级条件语句ifeq是错误的——define定义的函数是文本替换模板,ifeq作为Makefile的语法结构,无法在函数展开时被正确解析执行,导致所有条件判断失效,直接走到else分支;同时参数传递的解析也因为语法错误出现异常(错误信息中第二个参数变成soc就是语法混乱导致的)。
修复方案
方案1:使用Makefile内置函数实现条件判断(推荐)
用Makefile原生的$(if)、$(filter)函数实现逻辑,完全符合Makefile函数的文本替换逻辑:
define set_target_dts $(if $(filter $(1),virgo gemini), \ $(info Building for $(shell echo $(1) | tr '[:lower:]' '[:upper:]')), \ $(error Please select the correct target... (valid targets: virgo/gemini)) \ ) $(eval \ DTS_FILE_NAME := $(1)$(if $(filter $(2),soc_prototype),_soc_proto,).dts \ ) $(info Building for $(if $(filter $(2),soc_prototype),soc prototype,soc)) endef
方案2:改用Shell条件判断(适合习惯Shell语法的场景)
如果想保留echo的输出逻辑,可在函数中调用Shell的条件判断,注意Makefile变量赋值需要用$(eval):
define set_target_dts @echo "Building for $(shell echo $(1) | tr '[:lower:]' '[:upper:]')" $(eval \ if [ "$(2)" = "soc_prototype" ]; then \ echo "Building for soc prototype"; \ DTS_FILE_NAME=$(1)_soc_proto.dts; \ else \ echo "Building for soc"; \ DTS_FILE_NAME=$(1).dts; \ fi; \ ) $(if $(filter $(1),virgo gemini),, \ $(error Please select the correct target... (valid targets: virgo/gemini)) \ ) endef
调用验证
执行$(call set_target_dts,virgo,soc_prototype)后,会正确输出:
Building for Virgo Building for soc prototype
同时DTS_FILE_NAME会被赋值为virgo_soc_proto.dts。
关键注意事项
define函数本质是文本替换,所有逻辑必须用Makefile内置函数或Shell命令实现,不能直接嵌套Makefile的ifeq/else等顶级语法。- 要修改Makefile全局变量(比如
DTS_FILE_NAME),必须用$(eval)命令,否则函数内的赋值仅在函数展开的局部上下文生效。 - 参数
$(1)、$(2)的引用要确保在函数展开时被正确解析,避免语法混乱导致参数丢失。
内容的提问来源于stack exchange,提问作者Sheikh Muhammad Junaid Aslam
相关产品推荐
相关产品推荐

