makefile--变量的应用(下)

变量的应用(下)


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

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

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

7_1.PNG

在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)"

7_2.PNG

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

var := var_start

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

makefile2

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

7_3_1.PNG

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

export var := var_start

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

makefile2

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

7_3_2.PNG

示例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)"

7_3_3.PNG

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)"

7_4_1.PNG

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

var := var_start
test : var := var_test

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

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

7_4_2.PNG

4. 模式变量

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

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

new := new_start
%e : override new := new_e

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

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

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

7_5_1.PNG

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

new := new_start
%e : override new := new_e

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

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

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

7_5_2.PNG

小结

  • makefile中的三种变量:
  • 全局变量:makefile外部定义的环境变量
  • 文件变量:makefile中定义的变量
  • 局部变量:指定目标的变量
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 来自陈浩的一片老文,但绝对营养。 示例工程:3 个头文件*.h,和 8 个 C 文件*.c。 初 编译过程,源文件...
    周筱鲁阅读 10,148评论 0 17
  • 1.Makefile规范 target 这 一 个 或 多 个 的 目 标 文 件 依 赖 于prerequisi...
    G风阅读 5,933评论 0 3
  • 使用变量 在Makefile中的定义的变量,就像是C/C++语言中的宏一样,他代表了一个文本字串,在Makefil...
    Stan_Z阅读 6,377评论 0 11
  • 莎伦 2009-11-29 19:36 昨晚上梦见有人说我偷了他们的面条,真的特别生气,我也没有辩解,也好像迷迷糊...
    lijutong_010阅读 1,397评论 0 0
  • “所有的悲剧都由一场死亡来结束,所有的喜剧都由一场婚礼来终了。” ——拜伦《唐璜》 我在跋...
    Stellavallis阅读 2,688评论 0 0