Learn to Write Your Makefile

[實驗目的]

1. 掌握基本的Linux下makefile的編寫技能

2. 能夠閱讀常見的makefile


[實驗任務]

在linux平臺上編譯Sonia的一個project:

    [Sonia] Implementation of Huffman Algorithm

將上述工程文件編譯成可執行文件huffman 


[基本原理]

1. 依賴關係分析

1) main.cpp   <---  h_tree.h

於是,生成main.o要求: gcc  -c main.cpp  h_tree.h -o main.o

2) h_tree.cpp <--- h_tree.h

於是,生成h_tree.o要求: gcc  -c h_tree.cpp  h_tree.h -o h_tree.o

3) 而生成最終的可執行文件huffman需要將main.o 和 h_tree.o鏈接起來

於是有: gcc  main.o  h_tree.o -o huffman

由上述分析,可得基本的makefile如下:

huffman: main.o  h_tree.o
        g++ main.o h_tree.o -o huffman

main.o: main.cpp  h_tree.h
        g++ -c main.cpp -o main.o

h_tree.o: h_tree.cpp h_tree.h
        g++ -c h_tree.cpp -o h_tree.o

2. 詳細解析

上述makefile中包含了三條如下形式的規則:

**************************************************************************

target: dependenc_file1  dependenc_file2  ... dependenc_filen

<Tab><linux command>

**************************************************************************

main.o: main.cpp  h_tree.h
        g++ -c main.cpp -o main.o

1) main.o 爲要生成的目標

2)main.cpp  h_tree.h: 指明爲生成main.o的依賴項

3) g++ -c main.cpp -o main.o: 生成main.o需要執行的linux命令

注意:

1)makefile的linux命令(如g++  ,  rm 等均需要以 Tab鍵(\t)開頭 );

2)  makefile的文件應命名爲"makefile"或“Makefile” ;

3)  若編寫的是c文件,則應調用c語言的編譯器gcc。


3. makefile的使用

在含有makefile的目錄下,鍵入命令 “make” 即可


4. 添加make clean

一般地,爲了方便地清除編譯產生的臨時文件,在makefile中會加入一個clean語句。 當欲清理之前編譯產生的臨時文件時,僅需使用命令“make  clean”即可。

最終的makefile爲:

huffman: main.o  h_tree.o
        g++ main.o h_tree.o -o huffman

main.o: main.cpp  h_tree.h
        g++ -c main.cpp -o main.o

h_tree.o: h_tree.cpp h_tree.h
        g++ -c h_tree.cpp -o h_tree.o

clean:
        rm -rf *.o huffman

注意:

rm -rf *.o huffman是一條命令,故也應該以Tab鍵開頭


[練習]

1. 爲

[Sonia] Implementation of a Binary Tree Sort in C

編寫makefile, 要求支持“make” 和 “make  clean” 命令

2. 編寫完makefile文件後,輸入make命令,觀察生成的文件

3. 輸入make clean命令,觀察消失的文件




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章