Makefile引用与环境变量

1、Makefile中的引用

一个makefile中引用另外一个makefile,其写法与C语言include 相似。 make 命令开始时,会搜寻 include 所包含的其它 Makefile,并把其内容安置在当前的位置。bash

使用隐晦规则来书写makefileui

include Makefile.hello
run: main.o hello.o test.o
    gcc -o run main.o hello.o test.o
.PHONY: clean
clean:
    -rm run *.o  
复制代码

Makefile.hellospa

hello.o: hello.c
    gcc -c hello.c
复制代码

运行结果:code

root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make run
cc    -c -o main.o main.c
gcc -c hello.c
cc    -c -o test.o test.c
gcc -o run main.o hello.o test.o
复制代码

Makefile文件可使用其余命名来区分,如Makefile.hello,若是要单独执行Makefile.hello,只须要make -f Makefile.hello 或者 make --file Makefile.hellocdn

include 其余makefile可包含路径,若是没有路径。blog

  • 优先在当前目录搜索
  • 其次若是使用make -I 路径 或者 make --include-dir 路径,会在参数指定的位置搜索
  • 最后默认路径(/usr/local/bin或者/usr/include)中搜索

若是找不到该文件,报错。get

root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make run
Makefile:1: Makefile.hello: No such file or directory
make: *** No rule to make target `Makefile.hello'. Stop. 复制代码

若是打算没法找到Makefile.hello文件也要进行执行下去,只需在include前加个减号string

-include Makefile.hello
复制代码

make会继续执行下去。it

2、环境变量

书中提到:可是在这里我仍是建议不要使用这个环境变量,由于只要这个变量一被定义,那么当你使用 make 时,全部的 Makefile 都会受到它的影响,这毫不是你想看到的。在这里提这个事,只是为了告诉你们,也许有时候你的 Makefile 出现了怪事,那么你能够看看当前环境中有没有定义这个变量。io

环境变量和自定义变量 -》相似于“全局变量”和“局部变量” 建立个环境变量CWR

export CWR=666
复制代码

经过env来查看全部环境变量

image
Makefile中输出该变量

cwr:
    @echo $(CWR)
复制代码

@ 做用关闭命令回显 运行结果:

root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make cwr
666
复制代码

在Makefile中定义该变量

CWR = 233
cwr:
    @echo $(CWR)
复制代码

运行结果:

root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make cwr
233
复制代码

系统环境变量值被覆盖。 书中反复强调:不推荐把许多的变量都定义在系统环境中,这样,在咱们执行不用的Makefile 时,拥有的是同一套系统变量,这可能会带来更多的麻烦。

不过我看不少厂商在编译系统镜像前,都会先source 一下厂商写的环境变量脚本。估计也是为了让每一个模块共通的部分集中在环境变量中,使得模块的Makefile看起来更简洁更容易阅读。

相关文章
相关标签/搜索