close

敬告遊客:
以下內容枯燥無聊,若情非得已不建議進入。
若仍執意進入,當有頭暈嘔吐現象時請盡速離開本篇文章。


轉載來源自<工程師碎碎念>:http://blog.yam.com/ytha/article/16644244
引用內容如下:

現在小弟來說Makefile檔:
我們先建立一個簡單的程式: 名為 hello.c
如何寫一個最簡單的Makefile檔來編譯它?
# vim Makefile
進入編輯畫面:

# it is a test
all:hello.c
gcc hello.c -o hello
clean:
rm -f hello

存檔離開...當我們執行 # make, 就會把名為hello 的執行檔編譯出來
當我們輸入 # make clean, 就會把名為hello 的執行檔給刪除
而Makefile內的#符號指的是註解
ps: 注意: gcc hello.c -o hello 前的空白, 請使用tab鍵, 千萬別使用space鍵喔!!!!

再來複雜一點的:
我們再分別建立a.h, b.h, c.h, main.c, 2.c, 3.c 六個檔案
我們試著編譯它們
# vim Makefile1

mytest:main.o 2.o 3.o
gcc -o mytest 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就會去找第一行的必要條件: main.o 2.o 3.o, 當在目錄裡卻沒這三個檔, 所以make會在Makefile1往下找main.o/2.o/3.o分別把這三個檔案給編出來, 然後再把mytest這個執行檔給編譯出來, -f 是什麼? 第一次我們已建立一個名Makefile檔, 現在我們又建立一個Makefile1檔, 所以-f是告訴make去執行你所指定的Makefile檔...

再來把上面的變德更複雜一點: 加入變數/if判斷式/install
all: mytest
CC = gcc
INSTDIR = /usr/local/bin
INCLUDE = .
CFLAGS = -g -Wall -ansi

mytest: main.o 2.o 3.o
$(CC) -o mytest main.o 2.o 3.o
main.o: main.c a.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c main.c
2.o: 2.c a.h b.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c 2.c
3.o: 3.c b.h c.h
$(CC) -I$(INCLUDE) $(CFLAGS) -c 3.c

clean:
rm main.o 2.o 3.o

install: mytest
@if[ -d $(INSTDIR) ]; \
then \
cp mytest $(INSTDIR);\
chmod a+x $$(INSTDIR)/mytest; \
chmod og-w $(INSTDIR)/mytest; \
echo "Installed in $(INSTDIR)";\
else \
echo "Sorry, $(INSTDIR) does not exist";\
fi

哇, 有點多, 不過也一樣很容易理解:
all: mytest 為必要條件, 目錄裡沒有, 就會往下搜mytest: main.o 2.o 3.o
其它的上面已提過

CC = gcc
INSTDIR = /usr/local/bin
INCLUDE = .
CFLAGS = -g -Wall -ansi

此乃變數宣告, 使用變數方式: $(var)
INCLUDE=. 意指目前所在目錄之意

那這些個 -g -I -Wall是什麼東東?
-ansi : 程式要求依據ansi c標準
-I : 追加include檔案的搜尋路徑
-Wall : 編譯時顯示所有的警告訊息
-g : 編入除錯資訊(要使用GDB除錯一定要加)

install: 裡面全是shell程式的部份, 未來有空, 小弟會在此詳解
我先說個大概:
@if[ -d $(INSTDIR) ];
@ 指不要讓make install在執行時, 不要印出執行的細節
另外切記-d前面的空白處及後面R) ]空白處, 一樣一定要使用tab鍵, 不要使用space
-d 是要make判斷是該檔案是否為目錄且是存在的
cp, 不用說就是copy
chmod a+x 改變mytest 的權限屬性, 意指owner, group, other三個身份都可以執行這個檔案
chmod og-w 改變mytest 的權限屬性, 意指group, other三個身份都不可以編寫修改這個檔案
echo ".." 印出字串
fi 相當於endif的意思

這樣懂了嗎?

arrow
arrow
    全站熱搜

    calories 發表在 痞客邦 留言(0) 人氣()