Makefile基本规则及应用

本文介绍了Makefile的基础规则和使用方法,包括如何通过依赖关系构建目标文件,并提供了从简单到复杂的多个示例,帮助读者理解Makefile的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里介绍Makefile的基本规则和用法。

Makefile的基本规则为:

目标:依赖1 依赖2 ...

命令

如:

hello : hello.c a.c

gcc -o hello hello.c a.c

命令能够执行的条件是:

1)目标文件不存在

2)依赖被修改,即被编译的文件被修改,在这里指hello.c 和a.c

具体实现如下:

在命令行输入:vi hello.c然后编辑

  1 #include <stdio.h>
  2 extern void out( void );
  3 int main()
  4 {
  5     printf( "hello cs .\n" );
  6     out();
  7     return 0;
  8 }

在命令行输入 vi a.c

  1 #include <stdio.h>
  2 void out()
  3 {
  4     printf( "printf a.c\n" );
  5 }
在命令行输入 vi Makefile

  1 hello : hello.c a.c
  2     gcc -o hello hello.c a.c
然后执行:

[root@localhost makefile]# make
gcc -o hello hello.c a.c
[root@localhost makefile]# ./hello
hello cs .
printf a.c
[root@localhost makefile]# 

通常需要编译的文件比较多,往往只需要在文件被修改时编译即可,此时Makefile应为

  1 hello : hello.o a.o
  2     gcc -o hello hello.o a.o
  3 
  4 hello.o : hello.c
  5     gcc -o hello.o -c hello.c
  6 
  7 a.o : a.c
  8     gcc -o a.o -c a.c
-c表示只编译不链接
然后执行:

[root@localhost makefile]# make
gcc -o hello.o -c hello.c
gcc -o a.o -c a.c
gcc -o hello hello.o a.o
若需要删除编译产生的文件,编辑Makefile

  1 hello : hello.o a.o
  2     gcc -o hello hello.o a.o
  3 
  4 hello.o : hello.c
  5     gcc -o hello.o -c hello.c
  6 
  7 a.o : a.c
  8     gcc -o a.o -c a.c
  9 clean :
 10     rm -rf *.o hello

clean:后面的依赖不存在,表示执行make cleanrm -rf *.c hello命令始终执行

返回命令行,执行:

[root@localhost makefile]# ls
a.c  a.o  hello  hello.c  hello.o  Makefile
[root@localhost makefile]# make clean
rm -rf *.o hello
[root@localhost makefile]# ls
a.c  hello.c  Makefile
[root@localhost makefile]# 
Makefile文件的进一步改进

  1 hello : hello.o a.o
  2     gcc -o $@ $^
  3 
  4 %.o : %.c
  5     gcc -o $@ -c $<
  6 
  7 clean :
  8     rm -rf *.o hello

$@表示目标文件,$^表示编译两个文件$<表示编译的是一个文件。

然后执行:

[root@localhost makefile]# make
gcc -o hello.o -c hello.c
gcc -o a.o -c a.c
gcc -o hello hello.o a.o
[root@localhost makefile]# ls
a.c  a.o  hello  hello.c  hello.o  Makefile
[root@localhost makefile]# make clean
rm -rf *.o hello
[root@localhost makefile]# 
在此只是记录下目前学到的一些知识,具体的随后会做详细补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值