如何在Makefile中定义全局Shell函数? [英] How to define global shell functions in a Makefile?
问题描述
我想定义一个shell函数
I want to define a shell function
#!/bin/sh
test ()
{
do_some_complicated_tests $1 $2;
if something; then
build_thisway $1 $2;
else
build_otherway $1 $2;
fi
}
我可以在Makefile的每个规则中使用它的方式,例如:
in such a way that I can use it in every rule of my Makefile, such as:
foo: bar
test foo baz
要清楚,我希望shell函数成为Makefile的一部分.最优雅的方法是什么?如果您可以做到而无需递归调用make,则将获得加分.
To be clear, I want the shell function to be part of the Makefile. What is the most elegant way to do this? Bonus points if you can do it without calling make recursively.
背景:
我的实际问题是make -n
会产生非常长且不可读的输出.每个规则使用几乎相同的顺序的不可读的shell命令,并且有很多规则.上述解决方案将使make -n
的输出更加有用.
Background:
My actual problem is that make -n
produces a very long and unreadable output. Each rule uses almost the same sequence of unreadable shell commands, and there are many rules. The above solution would make the output of make -n
more useful.
推荐答案
此解决方案不依赖外部临时文件,也不会强制您修改SHELL
变量.
This solution does not rely on an external temporary file and does not force you to tinker with the SHELL
variable.
TESTTOOL=sh -c '\
do_some_complicated_tests $$1 $$2; \
if something; then
build_thisway $$1 $$2;
else
build_otherway $$1 $$2;
fi' TESTTOOL
ifneq (,$(findstring n,$(MAKEFLAGS)))
TESTTOOL=: TESTTOOL
endif
foo: bar
${TESTTOOL} foo baz
ifneq…endif
块在命令行上检查-n
标志,并将TESTTOOL
的扩展名设置为: TESTTOOL
,这易于阅读并且可以安全执行.
The ifneq…endif
block checks for the -n
flag on the command line and sets the expansion of TESTTOOL
to : TESTTOOL
which is easy to read and safe to execute.
如果可以的话,最好的解决方案是将shell函数转换为实际程序.
The best solution could be to turn the shell function into an actual program if this is an option for you.
这篇关于如何在Makefile中定义全局Shell函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!