目录
1. Lazy set: =
VARIABLE = value
最普通、标准的变量赋值。该变量在被使用的时候被展开(expanded)。
在value中如果涉及到其它变量时,会按在VARIABLE被使用的当前时刻的值进行展开,而不是用VARIABLE声明时的值。
如果这个变量之前已经被赋值有其它值则会被替换。如下例所示,注意HELLO_WORLD的值的变化。
HELLO = world
HELLO_WORLD = $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# This echoes "hello world!"
echo $(HELLO_WORLD)
2. Immediate set: :=
VARIABLE := value
Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.
与Lazy-set相比不同的是,这种赋值在声明时就已经进行展开了。比如说,如果value中涉及另外一个变量var1,而该声明以后var1的值有变化不会影响这个变量的取值。如下例所示,HELLO的值在HELLO_WORLD声明之后发生了变化,但是由于HELLO_WORLD在声明时已经完成了展开,因此不受此后HELLO的值的变化的影响。
HELLO = world
HELLO_WORLD := $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# Still echoes "world world!"
echo $(HELLO_WORLD)
HELLO_WORLD := $(HELLO) world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
如果VAR := value的右边value是literal而不是一个变量的话,则等价于=。
以下这个例子可以显示“:=”与“=”的区别:
# Filename: Makefile
x := foo
y := $(x) bar
x := later
a = foo
b = $(a) bar
a = later
test:
@echo x - $(x)
@echo y - $(y)
@echo a - $(a)
@echo b - $(b)
运行make test将得到:
x - later
y - foo bar
a - later
b - later bar
3. Lazy Set If Absent: ?=
VARIABLE ?= value
Setting of a variable only if it doesn't have a value. value
is always evaluated when VARIABLE
is accessed. It is equivalent to
ifeq ($(origin VARIABLE), undefined)
VARIABLE = value
endif
Using ?=
assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=
), it is still considered set I think. Otherwise, functions exactly like =
.
这种赋值方式类似于C或Python等编程语言中函数原型的声明中提供了缺省值,但是又有所不同。“?=
”意味着如果在此前这个变量没有被赋值的话,就使用这个值;而如果已经被赋值的话就忽略这个赋值。如下例所示是一个Makefile的例子:
#############################
# User variables
#############################
TB = tb_top
SEED = 1
TESTNAME ?= basic_test
如果后面在执行make命令时没有在命令行指定TESTNAME的话,则变量TESTNAME的值就采用“basic_test”,但是如果命令行参数指定了TESTNAME,如下所示:
>> make *** TESTNAME="burst_test"
则TESTNAME采用的值就是“burst_test”而不是“basic_test”.
4. Append: +=
VARIABLE += value
Using +=
is like using =
, but instead of replacing the value, the value is appended to the current one, with a space in between.
用+=表示追加赋值,将value追加在左边变量的原来值的后面,中间以空格隔开。类似于字符串的串接。如果左边变量之前没有被赋值,则相当于“=”同等功能。
HELLO_WORLD = hello
HELLO_WORLD += world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
更多的讨论可以参考以下连接。特别是关于recursive expansion的讨论。
Ref:
gnu make - What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?