在Makefile中使用变量

编程入门 行业动态 更新时间:2024-10-27 10:28:10
本文介绍了在Makefile中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个简单的Makefile.

Here is a simple Makefile.

FILENAME=test.`date +"%Y.%m.%d %H:%M:%S"`.txt test: @echo ${FILENAME} @sleep 2s @echo ${FILENAME}

make test的输出是

test.2013.02.18 15:30:23.txt test.2013.02.18 15:30:25.txt

问题在于,每次使用FILENAME时都在计算它.我希望只计算一次,并且在脚本运行时保持不变.我做错了吗?

The problem is that FILENAME is being calculated each time it is used. I want it to be calculated only once and be the same while script is running. Am I doing it wrong?

推荐答案

GNU Make具有两种变量.您已经使用了递归扩展的变量,但是想要一个简单扩展的变量.参见 www.gnu/software/make/manual/html_node/Flavors.html#Flavors

GNU Make has two flavours of variables. You have used a recursively-expanded variable, but you want a simply-expanded variable. See www.gnu/software/make/manual/html_node/Flavors.html#Flavors

对于当前的Makefile,变量包含确切的文本test.date +"%Y.%m.%d %H:%M:%S" .txt ,并且每次引用该变量时,该文本都会被逐字替换,因此您的Makefile等效于:

With your current Makefile, the variable contains the exact text test.date +"%Y.%m.%d %H:%M:%S".txt and every time you reference it that text gets substituted verbatim, and so your Makefile is equivalent to:

test: @echo test.`date +"%Y.%m.%d %H:%M:%S"`.txt @sleep 2s @echo test.`date +"%Y.%m.%d %H:%M:%S"`.txt

这样看来,外壳程序两次运行date命令应该很明显.

Seen like this it should be obvious that the shell runs the date command twice.

要获得所需的行为,您需要设置一个简单扩展的变量,并且需要在定义变量的位置运行shell命令,该命令不能使用反引号,因为反引号是shell的元字符,但Make会忽略它们,因此您可以使用Make的shell函数:

To get the behaviour you want, you need to set a simply-expanded variable and you need to run the shell command at the point where you define it, which can't use backticks because they are shell metacharacters but Make ignores them, so you use Make's shell function instead:

FILENAME := test.$(shell date +"%Y.%m.%d %H:%M:%S").txt

更多推荐

在Makefile中使用变量

本文发布于:2023-07-26 07:04:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1214863.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Makefile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!