在这里介绍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 clean时rm -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]#
在此只是记录下目前学到的一些知识,具体的随后会做详细补充。