Transcript 投影片1

Makefile
Speaker : Ya-Ling Wang
Date : 2012/7/25
Outline
•
•
•
•
•
•
•
•
執行檔如何產生
指令編譯
Make 簡介
Make 負責的範圍
Make 運作的流程
Makefile 基本規則
Make 指令用法
Makefile 進階規則
2
2012/7/25
執行檔如何產生
• 建置(build)執行檔 = 編譯 + 連結
• 編譯器(compiler)
– 把原始碼重新編成與翻譯為機械碼
– 機械碼(object code),俗稱 binary code
• .obj 檔案
• 連結器(linker)
– 把多份機械碼合併成執行檔
– 更正這些機械碼之間的參考位址(address)。
3
2012/7/25
執行檔如何產生 Cont.
C/C++
(.c, .cpp)
Compiler
編譯器
Object File
(.o)
Header Files
(.h)
Linker
鏈結器
Executable
File
Library
(.so, .a)
4
2012/7/25
指令編譯
UNIX上的編譯器
(GNU Compiler
Collection)
執行檔檔名
gcc –o hello hello.c
-o : output file
指定欲編出的執行檔
被編譯的原始檔
(.c/.cpp)
5
2012/7/25
Make簡介
• 在軟體開發中,make是一個工具程式(Utility
software),經由讀取叫做「makefile」的文件,自
動化建構軟體。
• 為什麼要用Make?
– 幫助程式編譯的工具
– 如果只是針對幾個檔案進行修改,卻要將整個程式重
新編譯,不但浪費時間也相當沒有效率
– 幫助我們判斷哪些需要重新編譯,哪些不用
• 優點
– 寫一次, 可以重複使用
– 重新編譯時,只編修改過的檔案
– 適合多個檔案,複雜的專案
6
2012/7/25
Make負責的範圍
C/C++
(.c, .cpp)
Compiler
編譯器
Object File
(.o)
Header Files
(.h)
Linker
鏈結器
Executable
File
Library
(.so, .a)
7
2012/7/25
Make的運作流程
在command line中輸入make
尋找目前目錄下的Makefile
按照Makefile中描述來執行工作
8
2012/7/25
Makefile基本規則
工作目標
必要條件
Target : Prerequisites
Command
一定要tab
執行命令
9
2012/7/25
Makefile基本規則 Cont.
工作目標
沒有 必要條件
Target :
Command
一定要tab
執行命令
10
2012/7/25
Makefile Example - 1
工作目標
必要條件
如果有Header File也要
放在必要條件裡
hello: hello.c hello.h
gcc –o hello hello.c
一定要tab
執行命令
11
2012/7/25
Makefile Example - 2
工作目標
必要條件
clean:
rm -rf hello
一定要tab
執行命令
12
2012/7/25
Make 指令用法
工作目標
(注意:如果空白,會執行
Makefile裡第一個目標)
make指令
make Target
13
2012/7/25
Makefile Example - Make 指令用法
欲編出的執行檔
(注意不要寫成hello.c)
make hello
14
2012/7/25
編譯多個檔案
Target 1: Prerequisites1
Command1
Target 2: Prerequisites2
Command2
從
上
到
下
注意不是每個
都會做
Target 3: Prerequisites3
Command3
…
15
2012/7/25
Makefile Example – 多個檔案
最終目標慣用all
習慣先編成
Object file
all: main.o file1.o file2.o
gcc –o main main.o file1.o file2.o
main.o: main.c
gcc -c main.c
file1.o: file1.c
gcc -c file1.c
file2.o: file2.c
gcc -c file2.c
16
2012/7/25
編譯的參數
• -c
– 編譯但不進行鏈結,會產生一個跟原始碼相同名稱但副檔
名為.o的目的檔。
• -o
– 生成執行檔,file name 沒指定時,預設檔名為 a.out。
• -g
– 把偵錯資訊也編譯進去
– 當你有需要使用GDB軟體進行偵錯,必須加入-g使GDB能夠
讀取。一般情況下可以不用-g,因為他也會增加binary大小。
• -Wall
– 顯示警告訊息
– 使用這個參數會在編譯時顯示更多的警告訊息。這個參數
相當有用,特別是找不到libs/headers之類的問題。
17
2012/7/25
設定變數
gcc: hello.c
gcc -Wall -g –o hello hello.c
CC= gcc
CFLAGS = -Wall -g
TARGET = hello
$(TARGET): hello.c
$(CC) $(CFLAGE) (INPATH) –o hello hello.c
18
參考文件
•
•
•
•
•
Make & Autotools PPT by吳孟寰
Make 語法指令
http://en.wikipedia.org/wiki/Make_(software)
http://www.csie.nctu.edu.tw/~skyang/
The Makefile utility
19
2012/7/25
Demo
Compiler
編譯器
hello.o
(.o)
hello.c
(.c or .cpp)
Linker
鏈結器
Library
(.so, .a)
good
Executable File
Compiler
編譯器
test.c
(.c or .cpp)
test.o
(.o)
20
2012/7/25
Exercise
• 如果Makefile的必要條件裡需要填很多個程
式檔,什麼方法可以讓它換行?
• 當make指令不帶參數時,會指令哪個目標?
• 自行編寫一個makefile,程式內容包含兩
個.cpp / .c 檔案與一個 .h 檔案,使用make
指令成功產生執行檔
– 若第二次修改了一個 .cpp,重新執行make會
顯示什麼訊息?
• 執行make clean刪除所有相依檔案
21
2012/7/25