在规则执行时定义make变量 [英] Define make variable at rule execution time

查看:47
本文介绍了在规则执行时定义make变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的GNUmakefile中,我想有一个使用临时目录的规则.例如:

In my GNUmakefile, I would like to have a rule that uses a temporary directory. For example:

out.tar: TMP := $(shell mktemp -d)
        echo hi $(TMP)/hi.txt
        tar -C $(TMP) cf $@ .
        rm -rf $(TMP)

按照书面规定,上述规则在解析时会创建一个临时目录.这意味着,即使我一直都不做out.tar,也会创建许多临时目录.我想避免/tmp堆满未使用的临时目录.

As written, the above rule creates the temporary directory at the time that the rule is parsed. This means that, even I don't make out.tar all the time, many temporary directories get created. I would like to avoid my /tmp being littered with unused temporary directories.

是否有一种方法可以导致仅在触发规则时定义变量,而不是在定义规则时定义变量?

Is there a way to cause the variable to only be defined when the rule is fired, as opposed to whenever it is defined?

我的主要思想是将mktemp和tar转储到shell脚本中,但这似乎有些难看.

My main thought is to dump the mktemp and tar into a shell script but that seems somewhat unsightly.

推荐答案

在您的示例中,只要规则被设置,就会设置TMP变量(并创建临时目录).评估.为了仅在实际触发out.tar时创建目录,您需要将目录创建移至以下步骤:

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

eval 函数对字符串的评估就像它已被手动输入到makefile中.在这种情况下,它将TMP变量设置为shell函数调用的结果.

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

编辑(针对评论):

要创建唯一变量,您可以执行以下操作:

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

这会将目标名称(在本例中为out.tar)放在变量之前,从而产生一个名称为out.tar_TMP的变量.希望这足以防止冲突.

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

这篇关于在规则执行时定义make变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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