/* main.c */ #include "a.h" ... /* 2.c */ #include "a.h" #include "b.h" ... /* 3.c */ #include "b.h" #include "c.h" ...
sin_value.c cos_value.c ,如何讓這個程式可以執行?
#%* 1. 先製作出四個目標檔: *) [guest@test guest]# gcc -c main.c [guest@test guest]# gcc -c haha.c [guest@test guest]# gcc -c sin_value.c [guest@test guest]# gcc -c cos_value.c #%* 2. 製作執行檔 main:*) [guest@test guest]# gcc -o main main.o haha.o sin_value.o \ > cos_value.o -lm -L/usr/lib -L/lib #%* 3. 執行:*) [guest@test guest]# ./main HaHa! I'm the King of the world 0.706825 0.707388
#%* 1. 先建立編譯的規則*)
[root@linux ~]# vi makefile
main: main.o haha.o sin_value.o cos_value.o
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
#%* 第二行的 gcc 之前是 <tab> 按鍵產生的空格*)
#%* 2. make 會主動讀取 makefile 內容,並編譯相關的執行檔*)
[root@linux ~]# rm -f main *.o %*<==先將之前的目標檔去除*)
[root@linux ~]# make
cc -c -o main.o main.c
cc -c -o haha.o haha.c
cc -c -o sin_value.o sin_value.c
cc -c -o cos_value.o cos_value.c
gcc -o main main.o haha.o sin_value.o cos_value.o -lm
#%* 3. 再執行一次 make *)
[root@linux ~]# make
make: `main' is up to date.
標的(target): 目標檔1 目標檔2 <tab> gcc -o 欲建立的執行檔 目標檔1 目標檔2
<tab> 需要在命令行的第一個字元;
<tab> 與空白:
<tab>;不能為空白。
# 為行首的文字都是註解。
myapp: main.o 2.o 3.o main.o: main.c a.h 2.o: 2.c a.h b.h 3.o: 3.c b.h c.h
$ gcc -MM main.c 2.c 3.c main.o: main.c a.h 2.o: 2.c a.h b.h 3.o: 3.c b.h c.h
all: myapp myapp.1
2.o: 2.c a.h b.h gcc -c 2.c #,以法則 gcc -c 2.c 產生目標項目 2.o
make [ -f makefile ] [ options ] ... [ targets ] ...,常用的選項及參數:
<filename>:告訴 make 該使用的 makefile 檔案。如果不使用這個選項, make 會依序尋找目錄中的 GNUmakefile, makefile, Makefile。
[root@dywOffice ~]# make targetfile
myapp: main.o 2.o 3.o
gcc -o myapp main.o 2.o 3.o
main.o: main.c a.h
gcc -c main.c
2.o: 2.c a.h b.h
gcc -c 2.c
3.o: 3.c b.h c.h
gcc -c 3.c
$ make -f Makefile1 make: *** No rule to make target 'main.c', needed by 'main.o'. Stop. $
$ touch a.h $ touch b.h $ touch c.h
/* main.c */
#include <stdlib.h>
/* 引用的標頭檔案,在 makefile 中,會有相依性關係。
#include "a.h"
extern void function_two();
extern void function_three();
int main()
{
/* 呼叫 function_two 和 function_three。 */
function_two();
function_three();
exit (EXIT_SUCCESS);
}
/* 2.c 定義 function_two 函式 */
#include "a.h"
#include "b.h"
void function_two() {
}
/* 3.c 定義 function_three 函式 */
#include "b.h"
#include "c.h"
void function_three() {
}
$ make -f Makefile1 gcc -c main.c gcc -c 2.c gcc -c 3.c gcc -o myapp main.o 2.o 3.o $
$ touch b.h $ make -f Makefile1 gcc -c 2.c gcc -c 3.c gcc -o myapp main.o 2.o 3.o $
$ rm 2.o $ make -f Makefile1 gcc -c 2.c gcc -o myapp main.o 2.o 3.o $
/* main.c */ #include "a.h" ... /* 2.c */ #include "a.h" #include "b.h" ... /* 3.c */ #include "b.h" #include "c.h" ...
#%* 1. 先建立編譯的規則*) $ vi makefile main: main.o ha1.o ha2.o → gcc -o main main.o ha1.o ha2.o #%* 2. make 會主動讀取 makefile 內容,並編譯相關的執行檔*) $ make
標的: 目標檔1 目標檔2 <tab> gcc -o 欲建立的執行檔 目標檔1 目標檔2
# 開頭。
Next: makefile 的變數
Up: 開發工具 - make 與
Previous: 編譯器與可執行檔
Contents
2017-06-14