Using variables in Makefile

陌路散爱 提交于 2019-12-11 10:11:28

问题


Here is a simple Makefile.

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

The output of make test is

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

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?


回答1:


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

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

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

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


来源:https://stackoverflow.com/questions/14939295/using-variables-in-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!