Makefile分步执行c语言编译过程

2023-08-16  本文已影响0人  CodingCode

假设a.out需要两个源文件t0.c和t1.c。

$ cat Makefile
     1  all: a.out
     2
     3  a.out: t0.o t1.o
     4      gcc -g $(PIE) -o $@ $^
     5      @echo "Done"
     6
     7  %.o:%.c
     8
     9  %.o:%.s
    10      gcc -c -o $@ $<
    11
    12  %.s:%.i
    13      gcc -S -o $@ $<
    14
    15  %.i:%.c
    16      gcc -E -o $@ $<

运行:

$ make
gcc -E -o t0.i t0.c
gcc -S -o t0.s t0.i
gcc -c -o t0.o t0.s
gcc -E -o t1.i t1.c
gcc -S -o t1.s t1.i
gcc -c -o t1.o t1.s
gcc -g  -o a.out t0.o t1.o
Done
rm t0.i t1.i t0.s t1.s

几点说明:

  1. 行7的作用是屏蔽缺省的.c->.o的编译,否则make会自动使用这个规则,而导致不按照这个完整的编译路径进行;例如,注释掉第7行:
cc    -c -o t0.o t0.c
cc    -c -o t1.o t1.c
gcc -g  -o a.out t0.o t1.o
Done

可见,隐式的.c->.o的规则被调用了,而没有使用Makefile里面定义的规则。

  1. 运行的最后rm t0.i t1.i t0.s t1.s,并不是我们定义的指令。
    这是make的缺省规则,它会自动删除中间文件,这里.i和.s都是中间文件。
    如果要保留这些中间文件,则需要使用.PRECIOUS指令:
.PRECIOUS: %.s %.i

How make decide an intermediate file:
A file cannot be intermediate if it is mentioned in the makefile as a target or prerequisite.

上一篇 下一篇

猜你喜欢

热点阅读