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