Makefile中变量的展开

在GNU make中对变量的赋值有两种方式:延时变量、立即变量。区别在于它们的定义方式和扩展时的方式不同,前者在这个变量使用时才扩展开,意即当真正使用时这个变量的值才确定;后者在定义时它的值就已经确定了。使用`=’,`?=’定义或使用define指令定义的变量是延时变量;使用`:=’定义的变量是立即变量。需要注意的一点是,`?=’仅仅在变量还没有定义的情况下有效,即`?=’被用来定义第一次出现的延时变量。

对于附加操作符`+=’,右边变量如果在前面使用(:=)定义为立即变量则它也是立即变量,否则均为延时变量。

例1.

//Makefile
.PHONY: all

Inst := [email protected]
Defer = [email protected]

all:
        @echo "Inst is $(Inst)"
        @echo "Defer is $(Defer)"


//$ make
Inst is ..d
Defer is .all.d

例2.

//Makefile
.PHONY: all

x = foo
y = $(x) b
x = later

xx := foo
yy := $(xx) b
xx := later
all:
        @echo "y is $(y)"
        @echo "yy is $(yy)"

//$ make
y is later b
yy is foo b

 例3.

对延迟变量在赋值导致错误。

//Makefile
.PHONY: all

CFLAGS = -d mm
CFLAGS += -t0x20000
CFLAGS = $(CFLAGS) -O

all:
        @echo "CFLAGS is $(CFLAGS)"

//$ make
Makefile:5: *** Recursive variable 'CFLAGS' references itself (eventually).  Stop.

例4.

对于同一变量采用不同的赋值解决例3中的错误

//Makefile
.PHONY: all

CFLAGS = -d mm
CFLAGS += -t0x20000
CFLAGS := $(CFLAGS) -O

all:
        @echo "CFLAGS is $(CFLAGS)"

//$ make
CFLAGS is -d mm -t0x20000 -O

猜你喜欢

转载自www.cnblogs.com/yangjiguang/p/11627760.html
今日推荐