简体   繁体   English

如何从 Makefile 的 shell 脚本中调用 function

[英]How to invoke a function in a shell script from a Makefile

I've a Makefile that contains a target to print a given variable:我有一个Makefile ,其中包含打印给定变量的目标:

print-%:
    @echo $*=$($*)

For example to print the value of variable CURDIR I just issue the following command:例如要打印变量CURDIR的值,我只需发出以下命令:

make print-CURDIR

And here's the result:结果如下:

CURDIR=/Users/j3d/Projects/myproject

Now I'd like to create a shell script that contains a set of common functions to be invoked from any Makefile ... and here's the modified version of the target above:现在我想创建一个 shell 脚本,其中包含一组要从任何Makefile调用的常用函数......这是上面目标的修改版本:

print-%:
    . ./make-util printvar $@

And here's make-util :这是make-util

#!/bin/sh

printvar()
{
    @echo $*=$(*)
}

Finally, running the script above...最后,运行上面的脚本......

j3d@j3ds-macbook-pro myproject % make print-CURDIR

... doesn't produce the expected result: ...不会产生预期的结果:

. ./make-utils CURDIR

How should I invoke the script function so that the given variable gets printed correctly?我应该如何调用脚本 function 以便正确打印给定的变量?

You can create a suite of make recipes (if you're using GNU make) that you can include and use in multiple makefiles, but you have to do it with make syntax, not shell syntax, because they are make recipes even if the recipe becomes a shell script after expansion.您可以创建一套 make recipes(如果您使用 GNU make),您可以在多个 makefile 中包含和使用它,但您必须使用make语法,而不是shell语法,因为它们是 make recipes 即使配方展开后变成 shell 脚本。

You can investigate the GNU make define statement and eval and call functions for ways to create user-defined functions in GNU make.您可以研究 GNU make define语句以及evalcall函数,以了解在 GNU make 中创建用户定义函数的方法。 For example you could write a makefile like this:例如,您可以像这样编写 makefile:

$ cat macros.mk
print-%:
        @echo $*=$($*)

then in your other makefiles you could use:然后在你的其他makefile中你可以使用:

include macros.mk

and you'd automatically get that rule available.并且您会自动获得该规则。

There are lots and lots of possibilities here but the details depend on what you want to do.这里有很多很多的可能性,但细节取决于你想做什么。

You are nearly there:你快到了:

Since you are passing the name of the function as first parameter, you could do a由于您将 function 的名称作为第一个参数传递,因此您可以执行

#!/bin/sh
printvar()
{
  @echo $*=$(*)
}
"$1"

to execute the function.执行 function。 If you want more safety (to catch cases where you pass by mistake some dangerous command instead of a function name), you could do a如果您想要更多安全性(以捕获错误传递一些危险命令而不是 function 名称的情况),您可以执行

[ "$1" = printvar ] && printvar
[ "$1" = other_function ] && other_function

instead.反而。

If you want to process your script Make-variables, you can pass them as additional parameters:如果要处理脚本 Make-variables,可以将它们作为附加参数传递:

func=$1
shift
[ "$func" = printvar ] && printvar "$@"
[ "$func" = other_function ] && other_function "$@"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM