Linux GCC make檔案的寫法–總結版

來源:互聯網
上載者:User

目錄結構為:

inc/hello.h

src/hello.c

main/main.c

Makefile

檔案內容為:

hello.h:

void hello(char name[]);<br />

hello.c:

#include <stdio.h></p><p>void hello(char name[])<br />{<br />printf("Hello %s!/n", name);<br />}<br />

main.c:

#include <stdio.h><br />#include "hello.h"<br />// The second hello.h should in ""<br />int main()<br />{<br /> hello("GCC");<br /> printf("Haha Linux Ubuntu!/n");<br /> return 0;<br />}<br />

Makefile:

# String declaration<br />objects = main.o hello.o</p><p># Command<br />app : $(objects)<br />cc -o app $(objects)<br />main.o : main.c hello.h stdio.h<br />cc -c $< -I ./inc<br />hello.o : hello.c stdio.h<br />cc -c $<</p><p># Search paths<br />vpath %.h /usr/include : inc<br />vpath %.c main : src</p><p># Clean the intermediate files<br />.PHONY : clean<br />clean :<br />rm app *~ $(objects)<br />

首先,需要明確一點,這裡面有兩個執行程式,一個make,一個gcc,在Makefile裡這兩個的語句也是分別佔1行的。

這裡最主要的是路徑的問題,因為不同的檔案在不同的目錄下面,所以要告訴程式檔案所在的路徑,而又有兩個程式需要告知,而兩個程式告知的方式又不同,所以這個問題一開始困擾了我好久,在好多好心人的協助下,終於明白了一點。

make的搜尋路徑設定方式為:vpath或VPATH,這個在許多資料裡都講過,而且這個是所有檔案都可以設定的,.c, .h還有其它的都可以。

gcc的搜尋路徑設定方式為(這個應該是只能設定標頭檔的搜尋路徑,因為是include):-I inc,

而.c檔案的搜尋路徑似乎不能設定,而只能在cc -c path/%.c中顯示的寫出,個人這麼理解。

而有一種方式是可以不用顯示的寫出的,而且也不用吧,%.c也寫出,就是用make的自動化變數

“$<”和“$@”則是自動化變數,“$<”表示所有的依賴目的地組(%.c),“$@”表示目的地組(%.o)。

(是make的變數,檔案在目前的目錄沒有找到的話,會自動搜尋vpath中設定的路徑,如果不用這個那麼如果.c在不在目前的目錄下,-c後面要指明目錄位置,用這個後,可以在vpath中指明即可)

因為是make的變數,所以用vpath設定的make的路徑在這裡面就起作用了,不用再顯示的指明.c的路徑了。而且這樣寫起來,更簡潔。

 

最近在看《深入理解電腦系統》網上下載的代碼都是在Linux上跑的,呵呵,所以得自己寫Makefile,所以,研究了一下,終於整明白了一點了,呵呵~~~

下載的代碼用這個Makefile檔案可以很方便的編譯:

# String declaration<br />path = netp<br />app = echoclient<br />objects = $(app).o csapp.o</p><p># Command<br />$(app) : $(objects)<br />cc -o $(app) $(objects)<br />$(app).o : $(app).c csapp.h<br />cc -c $< -I include<br />csapp.o : csapp.c csapp.h<br />cc -c $< -I include</p><p># Search paths<br />vpath %.h /usr/include : include<br />vpath %.c src : $(path)</p><p># Clean the intermediate files<br />.PHONY : clean<br />clean :<br />rm $(app) *~ $(objects)<br />

只需要修改path和app字串即可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.