http://www.cnblogs.com/sld666666/archive/2010/04/08/1707789.html
一個(gè)簡(jiǎn)單的makefile示例及其注釋
posted @ 2010-04-08 21:29 sld666666 閱讀(698) 評(píng)論(2)
相信在unix下編程的沒(méi)有不知道m(xù)akefile的,剛開(kāi)始學(xué)習(xí)unix平臺(tái)下的東西,了解了下makefile的制作,覺(jué)得有點(diǎn)東西可以記錄下。
下面是一個(gè)極其簡(jiǎn)單的例子:
現(xiàn)在我要編譯一個(gè)Hello world,需要如下三個(gè)文件:
1. print.h
#include<stdio.h>
void printhello();
2. print.c
#include"print.h"
void printhello(){
printf("Hello, world\n");
}
3. main.c
#include "print.h"
int main(void){
printhello();
return 0;
}
好了,很簡(jiǎn)單的程序了。如果我們想要編譯成功需要哪些步驟呢?
我認(rèn)為在這里需要理解的就兩步:
# 為每一個(gè) *.c文件生成 *o文件。
# 連接每一個(gè)*o文件,生成可執(zhí)行文件。
下面的makefile 就是根據(jù)這樣的原則來(lái)寫(xiě)的。
一:makefile 雛形:
#makefile的撰寫(xiě)是基于規(guī)則的,當(dāng)然這個(gè)規(guī)則也是很簡(jiǎn)單的,就是:
#target : prerequisites
command //任意的shell 命令
實(shí)例如下:
makefile:
helloworld : main.o print.o #helloword 就是我們要生成的目標(biāo)
# main.o print.o是生成此目標(biāo)的先決條件
gcc -o helloworld main.o print.o#shell命令,最前面的一定是一個(gè)tab鍵
mian.o : mian.c print.h
gcc -c main.c
print.o : print.c print.h
gcc -c print.c
clean :
rm helloworld main.o print.o
OK,一個(gè)簡(jiǎn)單的makefile制作完畢,現(xiàn)成我們輸入 make,自動(dòng)調(diào)用Gcc編譯了, 輸入 make clean就會(huì)刪除 hellowworld mian.o print.o
二:小步改進(jìn):
在上面的例子中我們可以發(fā)現(xiàn) main.o print.o 被定義了多處,我們是不是可以向C語(yǔ)言中定義一個(gè)宏一樣定義它呢?當(dāng)然可以:
makefile:
objects = main.o print.o #應(yīng)該叫變量的聲明更合適
helloworld : $(objects) //聲明了變量以后使用就要$()了
gcc -o helloworld$(objects)
mian.o : mian.c print.h
gcc -c main.c
print.o : print.c print.h
gcc -c print.c
clean :
rm helloworld $(objects)
修改完畢,這樣使用了變量的話在很多文件的工程中就能體現(xiàn)出方便性了。
三:再進(jìn)一步:
再看一下,為沒(méi)一個(gè)*.o文件都寫(xiě)一句gcc -c main.c是不是顯得多余了,能不能把它干掉?而且 main.c 和print.c都需要print.h,為每一個(gè)都寫(xiě)上是不是多余了,能不能再改進(jìn)?
能,當(dāng)然能了:
makefile:
objects = main.o print.o
helloworld : $(objects)
gcc -o helloworld$(objects)
$(objects) : print.h # 都依賴print.h
mian.o : mian.c #干掉了gcc -c main.c 讓Gun make自動(dòng)推導(dǎo)了。
print.o : print.c
clean :
rm helloworld $(objects)
好了,一個(gè)簡(jiǎn)單的makefile就這樣完畢了,簡(jiǎn)單吧。
=========華麗的分割線=========
還有一個(gè)網(wǎng)絡(luò)人氣很高的makefile教程(更詳細(xì)):
http://blog.csdn.net/haoel/archive/2004/02.aspx
跟我一起寫(xiě) Makefile - 陳皓
還有法語(yǔ)版本的makefile介紹:
http://gl.developpez.com/tutoriel/outil/makefile/
Introduction à Makefile