Makefile的call函数

本文通过实例详细介绍了Makefile中的call函数使用方法。探讨了如何定义多行变量并通过call函数调用,解释了$@自动化变量的作用及其实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了个例子来研究Makefile的call函数:

#define a multiline variable
define target 
	echo $@
	echo $@
endef

#define the target which is the first target, so default target
all:
	$(call target,all)

#define the second target, we must explicitly make it
clean:
	$(call target,clean)	

#declare that all and clean are phony targets
.PHONY: all clean

执行make或make all的结果是:

echo all
all
echo all
all


执行make clean的结果是:

echo clean
clean
echo clean	
clean

其实源代码可以这么写的:

#define a multiline variable
define target 
	echo $@
	echo $@
endef

#define the target which is the first target, so default target
all:
	$(call target)

#define the second target, we must explicitly make it
clean:
	$(call target)	

#declare that all and clean are phony targets
.PHONY: all clean

结果跟上面一样。


小结:Makefile中的第一个目标是最终目标,是make默认执行的目标,call函数会以此调用多行变量的每一个(此处是make命令,所以会被执行了)。然后$@自动化变量在make执行是会被赋值为当前的目标。

### Makefile 中自定义函数的创建与调用 在 `Makefile` 中,可以通过 `call` 函数来实现自定义函数的功能。具体来说,可以利用变量存储模板代码,并通过 `call` 函数动态传递参数并执行逻辑。 #### 定义自定义函数 自定义函数通常被定义为一个带有特定命名约定的变量。该变量的内容实际上是一个字符串模板,其中包含了占位符形式的参数名(如 `$1`, `$2`)。这些参数将在调用时由实际值替代。 以下是定义自定义函数的一个基本示例: ```makefile define my_function echo "Parameter 1 is $1" echo "Parameter 2 is $2" endef ``` 在此例子中,`my_function` 是一个名为 `my_function` 的自定义函数[^2]。它接受两个参数 (`$1` 和 `$2`) 并打印它们的值。 #### 调用自定义函数 要调用上述定义好的函数,需使用 `call` 函数。其语法如下所示: ```makefile $(call function_name,arg1,arg2,...) ``` 对于前面定义的 `my_function`,我们可以这样调用它: ```makefile all: $(call my_function,Hello,World) ``` 当运行此目标时,会输出以下内容: ``` echo "Parameter 1 is Hello" echo "Parameter 2 is World" Parameter 1 is Hello Parameter 2 is World ``` 这表明成功地将 `"Hello"` 和 `"World"` 替换了模板中的 `$1` 和 `$2` 参数位置。 #### 使用 eval 动态生成规则或变量 除了简单的参数替换外,还可以结合 `eval` 函数进一步增强灵活性。例如,可以根据传入的不同参数动态生成新的规则或者重新设置某些变量。 下面展示了一个稍微复杂的场景——基于文件扩展名自动构建编译命令的例子: ```makefile define compile_rule_template build_%.$(suffix): %.c gcc -o build_$*.out $$< -l$$@ endef SUFFIXES := c cpp java py $(foreach suffix,$(SUFFIXES),\ $(eval $(call compile_rule_template,$(suffix)))) ``` 在这个片段里,先定义了一条通用的编译规则模板 `compile_rule_template`,然后遍历所有可能的语言后缀列表 `(SUFFIXES)` ,并通过 `eval` 将具体的实例化版本应用到最终的目标集合上。 ### 总结 通过组合 `define`/`endef` 块以及 `call` 和 `eval` 等工具,可以在 `Makefile` 文件内部轻松实现高度可重用性和定制化的功能模块设计。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值