如何使用GNU Make为每个目标运行前和后配方? [英] How to run pre- and post-recipes for every target using GNU Make?

查看:67
本文介绍了如何使用GNU Make为每个目标运行前和后配方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

make中,是否可以为每个目标定义前食谱和后食谱?

In make, is it possible to define a pre- and post-recipe for every target?

我要(隐式)在显式配方的第一行上方插入前食谱,然后(隐式)在显式配方的最后一行之后插入后食谱.

I want to (implicitly) insert the pre-recipe just above the first line of the explicit recipe and then (implicitly) insert the post-recipe after the last line in the explicit recipe.

使用正则表达式插入行会很容易,但是隐式行会更干净.

It would be pretty easy to do it using regular expressions to insert lines but implicit ones would be so much cleaner.

推荐答案

您可以创建一个特殊的帮助程序外壳,该外壳程序在其输入脚本之前和之后执行所需的前后动作,并告诉make使用该外壳程序执行以下操作:执行食谱(使用 SHELL 变量).

You can create a special helper shell that executes the desired pre- and post- actions before and after its input script and tell make to use that shell for executing the recipes (use the SHELL variable to that end).

此外,如果您使用的是多行食谱,则必须启用

Besides, if you are using multiline recipes, you will have to enable the .ONESHELL mode.

注意事项:在此模式下,失败的命令(最后一个命令除外)不会失败 规则,所以您要么必须将命令与&&联接,要么附加 || exit 1到每个命令的末尾,或者使用-e运行真正的shell 选项.

Caveat: in this mode a failed command (except the last one) doesn't fail the rule, so you either have to join the commands with &&, or append || exit 1 to the end of each command, or run the real shell with the -e option.

示例:

发布前

#!/bin/bash

preaction()
{
    echo "Pre-action"
}

postaction()
{
    echo "Post-action"
}

preaction && /bin/bash "$@" && postaction

makefile

SHELL=./pre-post-shell

all: Hello Bye

.ONESHELL:

Hello:
    @echo Hello
    echo Hello again

Bye:
    @echo Bye

输出:

$ make
Pre-action
Hello
Hello again
Post-action
Pre-action
Bye
Post-action

这篇关于如何使用GNU Make为每个目标运行前和后配方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆