如何获得“至多一次"变量赋值中的语义? [英] How to get "at most once" semantics in variable assignments?

查看:127
本文介绍了如何获得“至多一次"变量赋值中的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Shell命令有时需要很长时间才能运行,因此您可能不想执行VAR = $(shell slow-cmd)(使用=时,每次引用变量时都会运行slow-cmd).使用VAR := $(shell slow-cmd)可能很有用,但是如果您构建的目标不需要扩展变量,则对slow-cmd的调用将比需要的多.在下面的makefile(带有gnu-make)中,您可以得到所需的行为:为V2定义值的shell命令从不会被多次调用,而对于目标foo则根本不会被调用.但这是一个令人发指的冲突.有没有更合理的方法来确保仅在需要时定义变量,而绝不对变量进行多次评估?

Shell commands sometimes take a long time to run, so you may not want to do VAR = $(shell slow-cmd) (with =, the slow-cmd will be run every time the variable is referenced). Using VAR := $(shell slow-cmd) can be useful, but if you are building a target that does not ever need the variable expanded, you will get one more invocation of the slow-cmd than is needed. In the following makefile (with gnu-make), you can get the desired behavior: the shell command to define a value for V2 is never invoked more than once, and for the target foo it is not invoked at all. But this is a heinous kludge. Is there a more reasonable way to ensure that a variable is only defined when needed, but never evaluated more than once?

V1 = $(shell echo evaluating V1 > /dev/tty; echo V1 VALUE)

all: foo bar V2
        @echo $(V1) $@
        @echo $(V2) $@

foo:
        @echo $(V1) $@

bar: V2
        @echo $(V1) $@
        @echo $(V2) $@

V2:
        $(eval V2 := $(shell echo evaluating V2 > /dev/tty; echo V2 VALUE))

.PHONY: all foo bar

推荐答案

没有技巧就无法做到这一点,但是有一种比您正在使用的方法更简洁的方法(也许).您可以使用:

There's no way to do it without tricks, but there's a cleaner way (maybe) than you're using. You can use:

V1 = $(eval V1 := $$(shell some-comand))$(V1)

有关此功能的详细信息和解释,请参见此页面.

For more details and explanation of exactly how this works see this page.

这篇关于如何获得“至多一次"变量赋值中的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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