gpt4 book ai didi

Makefile:如何仅设置一次 LOGFILE =`date +' test_%m.%d_%H.%M.%S.log'` 变量?

转载 作者:行者123 更新时间:2023-12-01 13:49:06 26 4
gpt4 key购买 nike

我喜欢将测试程序的输出记录到带有时间戳的日志文件中。

我创建了以下 Makefile,但它不起作用。 “make”似乎在最后一刻根据需要计算 LOGFILE。

生成文件

LOGFILE=`date +'test_%m.%d_%H.%M.%S.log'`
export DLOG=$(LOGFILE)
test2:
echo DLOG=$$DLOG
echo DLOG=${DLOG}
sleep 2
echo DLOG=${DLOG}

做测试2

echo DLOG=$DLOG
DLOG=`date +'test_%m.%d_%H.%M.%S.log'`
echo DLOG=`date +'test_%m.%d_%H.%M.%S.log'`
DLOG=test_10.22_10.28.04.log
sleep 2
echo DLOG=`date +'test_%m.%d_%H.%M.%S.log'`
DLOG=test_10.22_10.28.06.log

我想找到让“make”只计算一次 LOGFILE 或 DLOG 变量的方法,并且我可以在 makefile 中的任何地方使用相同的值。可能吗?

最佳答案

这是因为您的变量的风格

有问题的手册部分是 The Two Flavors of Variables .

特别是

The first flavor of variable is a recursively expanded variable. Variables of this sort are defined by lines using ‘=’ (see Setting Variables) or by the define directive (see Defining Multi-Line Variables). The value you specify is installed verbatim; if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called recursive expansion.

To avoid all the problems and inconveniences of recursively expanded variables, there is another flavor: simply expanded variables.

Simply expanded variables are defined by lines using ‘:=’ or ‘::=’ (see Setting Variables). Both forms are equivalent in GNU make; however only the ‘::=’ form is described by the POSIX standard (support for ‘::=’ was added to the POSIX standard in 2012, so older versions of make won’t accept this form either).

所以你想在 LOGFILE 赋值或 DLOG 赋值(或两者)。

您还需要使用 make $(shell) 函数让 make 执行命令,而不是使用反引号让 shell(针对配方行运行)执行命令。

LOGFILE=$(shell date +'test_%m.%d_%H.%M.%S.log')
export DLOG:=$(LOGFILE)
test2:
echo DLOG=$$DLOG
echo DLOG=${DLOG}
sleep 2
echo DLOG=${DLOG}

这里要注意的重要一点是,这将导致 make 在 make 解析时而不是在配方执行时运行命令。

如果您不想要它(因为您可能不会运行该目标)或者您希望它计算配方执行时间,那么您需要在配方中执行命令并使用单个 shell(通过 line-continuation 或 .ONESHELL )或者您需要在配方中使用 $(eval) 来强制 make 仅在配方执行时扩展简单扩展的 make-level 变量。

关于Makefile:如何仅设置一次 LOGFILE =`date +' test_%m.%d_%H.%M.%S.log'` 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com