学习自狄泰软件学院唐佐临老师Makefile课程,文章中图片取自老师的PPT,仅用于个人笔记。
make clean 执行该语句,在此时的上下文当中,我们不希望 clean 是一个文件,我们更希望 clean是一个标签,把clean这个目标当做标签使用。
实验1
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
clean :
rm *.o hello.out
mhr@ubuntu:~/work/makefile1$ make
make: 'hello.out' is up to date.
mhr@ubuntu:~/work/makefile1$ make clean
rm *.o hello.out
mhr@ubuntu:~/work/makefile1$
实验2
在当前文件夹下创建一个 clean 文件,内容随意。并且再次执行 make clean
mhr@ubuntu:~/work/makefile1$ make clean
make: 'clean' is up to date.
mhr@ubuntu:~/work/makefile1$
为什么会这样?这是因为 在默认情况相下 make认为自己是处理文件的 make 以文件处理作为第一优先级,当 make clean 的时候,make 发现有 clean 文件并且是最新的,就没有必要执行对应的命令了。但是我们希望无论何时 make clean 的时候都会执行命令。怎么解决呢?
实验3
有了 伪目标就可以解决上面的问题了。
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
.PHONY : clean
clean :
rm *.o hello.out
同样当前路径存在一个 clean 文件
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$
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$
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make clean
rm *.o hello.out
mhr@ubuntu:~/work/makefile1$
技巧1 :.PHONY关键字
实验4
hello.out : 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
.PHONY : rebuild clean all
rebuild : clean all
all : hello.out
clean :
rm *.o hello.out
技巧2 绕开.PHONY关键字
问题 :为什么要绕开 .PHONY关键字呢?
答案:.PHONY关键字 是标准make里面才有的关键字,在GNU make 中是存在的。但是假设现在使用的不是标准的 GUN make,此时就没有 .PHONY关键字了。
实验5
hello.out : 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
clean : FORCE
rm *.o hello.out
FORCE :
$
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ ls
clean func.c main.c makefile
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$
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$
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make clean
rm *.o hello.out
mhr@ubuntu:~/work/makefile1$