linux应用编程-Makefile和gdb调试

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!。

<
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值