3.4 Makefile
在前面学会使用命令行来编译Linux程序。项目有hello.cpp、other.cpp、other.h文件。
方法1:命令行编译
g++ hello.cpp other.cpp -o hello
方法2:命令行编译链接
g++ -c hello.cpp -o hello.o
g++ -c other.cpp -o other.o
g++ hello.o other.o -o hello
我们发现每次编译都需要写这么多的命令行,实在太过于繁琐。有没有一种方法,将命令行写入一个脚本文件中,来自动执行呢?
3.4.1全量编译和增量编译
Makefile就是Linux中存放命令行的脚本文件,用来生成整个项目。
创建方法:创建文件名为Makefile;执行make -f Makefile或make会自动执行Makefile中的命令行。
Makefile格式:
目标(target):依赖(prerequiries)...
<Tab>命令(command)...
目标是需要生成的文件名;依赖是产生目标所需要的材料,可以不写;命令是生成目标所要执行的规则,即命令行。
方法3:Makefile
hello:
g++ hello.cpp other.cpp -o hello
方法4:Makefile
hello:
g++ -c hello.cpp -o hello.o
g++ -c other.cpp -o other.o
g++ hello.o other.o -o hello
全量编译:当某个文件变化时,所有文件重新编译。
增量编译:当某个文件变化时,只需要编译改变的文件。
方法5:全量编译
hello:hello.cpp other.cpp
g++ hello.cpp other.cpp -o hello
方法6:增量编译
hello:hello.o other.o
g++ hello.o other.o -o hello
hello.o:hello.cpp other.h
g++ -c hello.cpp -o hello.o
other.o:other.cpp other.h
g++ -c other.cpp -o other.o
最后加上清除的命令,如下所示。
方法7:
hello:hello.o other.o
g++ hello.o other.o -o hello
hello.o:hello.cpp other.h
g++ -c hello.cpp -o hello.o
other.o:other.cpp other.h
g++ -c other.cpp -o other.o
clean:
rm *.o hello
当执行make或make -f Makefile时,会执行前3条命令生成hello可执行文件;当执行make clean或make -f Makefile clean时,将执行rm命令,清除所有.o文件和hello文件。
3.4.2 Makefile中的注释、赋值和函数
在Makefile中使用#来注释,如# this is a test!。
<