在Linux系统中,使用make和makefile能简单明了的理顺各个源文件的关系,极大提高程序开发效率。
makefile作为描述文档一般包含以下几个部分:
1.显式规则
显示规定如何生成目标文件,所依赖的文件及生成的命令等。
2.隐式规则色
Linux系统支持一种基于文件拓展名的隐含规则(即文件名后缀的隐含规则),规定了如何将特定文件名后缀的文件(如.c文件),转换成另一种后缀的文件(如.o文件)。
.c : .o
$(cc) $(CFLAGS) $(CPPFLSGS) -c -o $@ $<
系统拓展名及其含义:
.o:目标文件
.c:源文件
.s:汇编文件
3.宏(变量)定义
makefile允许用简单的宏替换源文件及其编译信息,引用宏时必须在宏变量前加"$"号,如果变量名的长度超过一个字符(一个字符长度等于一个字节),变量要用“()”
4.注释
首行使用“#”便是注释,在makefile文件中要使用注释则需加“/"转义字符
makefile的基本语法规则如下:
目标文件 : 目标所依赖的文件
command
注意:如果command不和目标文件所在一行时,在command前要加tab键
接下来看个简单的例子:
1.定义一个fun.h头文件
1 #ifndef _FUN_H
2 #define _FUN_H
3
4 extern int fun1(void)
5 extern int fun2(void)
6 extern int fun3(void)
7
8 #endif
2.定义一个fun.c文件
1 #include<stdio.h>
2 int fun1()
3 {
4 printf("This is first function!\n");
5 return 0;
6 }
7
8 int fun2()
9 {
10 printf("This is second function!\n");
11 return 0;
12 }
13
14 int fun3()
15 {
16 printf("This is third function!\n");
17 return 0;
18 }
3.定义一个mian.c文件
1 #include<stdio.h>
2 #include<stdlib.h>
3 int main()
4 {
5 fun1();
6 fun2();
7 fun3();
8 return 0;
9 }
那么如何用makefile将几个文件编译连接在一起呢?
我们首先定义一个makefile
root@shen:~# vim makefile
1 edit : main.o fun.o
2 cc -o edit main.o fun.o
3 mian.o : main.c
4 cc -c mainn.c
5 fun.o : fun.c fun.h
6 cc -c fun.c
7 clean:
8 rm fun.o main.o
接着在shell中输入make即可编译
root@shen:~# make
cc -c -o main.o main.c
cc -c fun.c
cc -o edit main.o fun.o
最后运行:
root@shen:~# ./edit
This is first function!
This is second function!
This is third function!