makefile--变量的应用(下)

2,192 阅读1分钟

变量的应用(下)


1. 环境变量(全局变量)

  • makefile中能够直接使用环境变量的值
    定义了同名变量,环境变量将被覆盖
    运行make时指定"-e"选项,优先使用环境变量
    示例1
LOGNAME := other

test :
    @echo "LOGNAME => $(LOGNAME)"

直接使用环境变量的值
在Makefile中使用环境变量的优缺点: 优势: 环境变量可以在所有makefile中使用 劣势: 过多的依赖于环境变量会导致移植性降低


2. 变量在不同makefile之间的传递方式

  • 直接在外部定义环境变量进行传递
  • 使用export定义变量进行传递(定义临时环境变量)
  • 定义make命令行变量进行传递(推荐)

示例2_1--直接在外部定义环境变量进行传递 makefile

LOGNAME := other

test :
    @echo "LOGNAME => $(LOGNAME)"
    @echo "make another file"
    @$(MAKE) -f makefile2

makefile2

test :
    @echo "LOGNAME => $(LOGNAME)"

直接在外部定义环境变量进行传递

示例2_2--多个文件调用同一个变量不使用export makefile

var := var_start

test :
    @echo "make another file"
    @$(MAKE) -f makefile2

makefile2

test :
    @echo "var => $(var)"

多个文件调用同一个变量不使用export

示例2_3--使用export定义变量进行传递 makefile

export var := var_start

test :
    @echo "make another file"
    @$(MAKE) -f makefile2

makefile2

test :
    @echo "var => $(var)"

使用export定义变量进行传递

示例2_4--定义make命令行变量进行传递 makefile

var := var_start

test :
    @echo "make another file"
    @$(MAKE) -f makefile2
    @$(MAKE) -f makefile2 var:=$(var)

makefile2

test :
    @echo "var => $(var)"

定义make命令行变量进行传递*


3. 目标变量(局部变量)

  • 作用域只在指定目标及连带规则中
target : name <assignment> value
target : override name <assignment> value

示例3_1-目标变量,无依赖关系

var := var_start
test : var := var_test

test : 
    @echo "test:"
    @echo "var => $(var)"
    
another :
    @echo "another:"
    @echo "var => $(var)"

目标变量,无依赖关系

示例3_2-目标变量,连带依赖

var := var_start
test : var := var_test

test : another
    @echo "test:"
    @echo "var => $(var)"
    
another :
    @echo "another:"
    @echo "var => $(var)"

目标变量,连带依赖


4. 模式变量

  • 模式变量是目标变量的扩展
  • 作用域只在符合模式的目标及连带规则中
pattern : name <assignment> value
pattern : override name <assignment> value

示例4_1-模式变量-无依赖关系

new := new_start
%e : override new := new_test

test :
    @echo "test:"
    @echo "new => $(new)"
    
another :
    @echo "another:"
    @echo "new => $(new)"

rule :
    @echo "rule:"
    @echo "new => $(new)"

模式变量-无依赖关系
示例4_2-模式变量-连带依赖

new := new_start
%e : override new := new_test

test : another
    @echo "test:"
    @echo "new => $(new)"
    
another :
    @echo "another:"
    @echo "new => $(new)"

rule :
    @echo "rule:"
    @echo "new => $(new)"

模式变量-连带依赖


小结

  • makefile中的三种变量:
  • 全局变量:makefile外部定义的环境变量
  • 文件变量:makefile中定义的变量
  • 局部变量:指定目标的变量