学习自狄泰软件学院唐佐临老师Makefile课程,文章中图片取自老师的PPT,仅用于个人笔记。
1 Makefile 依赖规则
2 试验1 验证依赖规则1:当目标对应的文件不存在时,执行命令
3 实验3 验证依赖规则2:当依赖在时间上比目标新时,执行对应命令
4 实验4 验证依赖规则1:当目标对应的文件不存在时,执行命令
5 实验5 工程开发中可以将最终的可执行文件名 和 all 同时作为 makefile 中第一条规则的目标
实验1:
all : test
@echo "make all" //不打印语句本身,只打印执行结果
test : //没有依赖条件
@echo "make test"
mhr@ubuntu:~/work/makefile1$ make
make test
make all
mhr@ubuntu:~/work/makefile1$
过程:
all 依赖于 test,所以要完成 all 这个目标,必须保证 test这个目标存在,并且完成后续的命令,test作为目标 ,但是当前文件下 test没有对应的文件存在,所以根据依赖规则,当目标对应的文件不存在时,test目标所对应的命令会被执行。
实验2
可执行程序 hello.out 依赖于 func.o main.o
all : func.o main.o
gcc -o hello.out func.o main.o
func.o : func.c
gcc -o func.o -c func.c
main.o : main.c
gcc -o main.o -c main.c
func.c
#include "stdio.h"
void foo()
{
printf("void foo() : hello makefile\n");
}
main.c
extern void foo();
int main()
{
foo();
return 0;
}
mhr@ubuntu:~/work/makefile1$ make
gcc -o func.o -c func.c
gcc -o main.o -c main.c
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$ ls hello.out
hello.out
mhr@ubuntu:~/work/makefile1$ ./hello.out
void foo() : hello makefile
mhr@ubuntu:~/work/makefile1$
实验3
在实验2的基础上,略微修改 func.c,而main.c保持不变,再次执行 make
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
gcc -o func.o -c func.c
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$
这里只执行了
func.o : func.c
gcc -o func.o -c func.c
并没有执行
main.o : main.c
gcc -o main.o -c main.c
是因为 根据依赖规则第二条:当依赖在时间上比目标新时,执行对应命令。此处的 func有的改动,状态是比上次生成的 func.o新的,所以会重新执行 gcc -o func.o -c func.c。
实验4
基于实验3,再次make 多次,发现每次都会之执行
all : func.o main.o
gcc -o hello.out func.o main.o
这是为什么呢?明明 func.o main.o 两个依赖都没有更新变化,为什么还会反复执行呢,不合理且没必要重新链接产生 hello.out啊。这是因为 根据依赖规则第一条 最终目标all 没有对应一个 具体的文件,所以make认为 all所对应的 命令必须执行。
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$ make
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$
实验5:
处理实验四 任何依赖都没有发生更新变化 仍然执行命令的 问题
修改 Makefile
hello.out all : func.o main.o
gcc -o hello.out func.o main.o
func.o : func.c
gcc -o func.o -c func.c
main.o : main.c
gcc -o main.o -c main.c
这样的好处就是,当任何依赖都没有发生变化更新的时候,make 的时候 就不会重新执行 gcc -o hello.out func.o main.o ,因为 make 已经发现了 最终目标 hello.out 在当前目录中存在对应的文件,所以又发现依赖没有变化 就不会命令了,当然 如果我们就是想重新执行 那么就执行 make all 依然会执行命令,原因如实验4所示。
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
make: 'hello.out' is up to date.
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make all
gcc -o hello.out func.o main.o
mhr@ubuntu:~/work/makefile1$