bash 使用 ENV 变量或默认值定义 Makefile 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24263291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define a Makefile variable using a ENV variable or a default value
提问by Natim
I am trying to do a simple thing:
我正在尝试做一件简单的事情:
TMPDIR ?= /tmp
test:
@echo $(TMPDIR)
This works if I run:
如果我运行,这会起作用:
$ make test
/tmp
It also works if I run:
如果我运行它也有效:
$ make test -e TMPDIR=~/tmp
/home/user/tmp
What can I do to also have it works for:
我该怎么做才能让它适用于:
$ TMPDIR=~/tmp make test
/home/user/tmp
回答by MadScientist
To follow up on my comments above, here's an example:
为了跟进我上面的评论,这里有一个例子:
T ?= foo
all:
: '$(T)'
Now if I run the Makefile in various ways, it behaves as we expect (I get foo
only if I don't set T
either on the command line or environment):
现在,如果我以各种方式运行 Makefile,它会按照我们的预期运行(foo
只有在我没有T
在命令行或环境中设置时才会得到):
$ make
: 'foo'
$ make T=bar
: 'bar'
$ T=bar make
: 'bar'
回答by Maxim Egorushkin
Variables specified on make command line override the values assigned in makefile:
在 make 命令行中指定的变量会覆盖在 makefile 中分配的值:
TMPDIR := "/tmp"
test:
@echo $(TMPDIR)
And then:
进而:
make TMPDIR=whatever
whatever
It is generally bad practice for makefiles to depend on environment variables, this is why passing variables in make command line is preferred.
makefile 依赖于环境变量通常是不好的做法,这就是为什么在 make 命令行中传递变量是首选的原因。
Another way is to use make or
function:
另一种方法是使用 makeor
函数:
X := $(or ${X},${X},abc)
all :
@echo ${X}
make
abc
X=def make
def
Actually, you should just stick to using ?=
assignment.
实际上,您应该坚持使用?=
赋值。
回答by kenorb
Here is a simple solution:
这是一个简单的解决方案:
SHELL := env TMPDIR=$(TMPDIR) $(SHELL)
TMPDIR ?= "/tmp"
all:
@echo $(TMPDIR)
which works for both scenarios: TMPDIR=new/path make
and make TMPDIR=new/path
.
这适用于两种情况:TMPDIR=new/path make
和make TMPDIR=new/path
。
回答by Natim
One of the thing you could do is:
你可以做的一件事是:
TMPDIR := "/tmp"
ifdef $$TMPDIR
TMPDIR := $$TMPDIR
endif
test:
echo $(TMPDIR)