C指標原理(14)-C指標基礎
make與makefile
make是一個工具程式(Utility software),經由讀取叫做“makefile”的檔案,自動化建構軟體。它是一種轉化檔案形式的工具,轉換的目標稱為“target”;與此同時,它也檢查檔案的依賴關係,如果需要的話,它會呼叫一些外部軟體來完成任務。它的依賴關係檢查系統非常簡單,主要根據依賴檔案的修改時間進行判斷。大多數情況下,它被用來編譯原始碼,生成結果程式碼,然後把結果程式碼連線起來生成可執行檔案或者庫檔案。
makefile的格式是:
#用“井”號表明註釋。 target(要生成的檔案): dependencies(被依賴的檔案) #命令前面用的是“tab”而非空格。 #誤用空格是初學者容易犯的錯誤! 命令1 命令2 命令3 . . . 命令n #可以使用“\”表示續行。注意,“\”之後不能有空格!
target通常是我們要生成的檔案的名字,擺放的順序不重要,但第一個target是預設的target。當make不帶引數時,自動執行第一個target。target也可以是要求make完成的動作,執行這種target後並不能得到和target同名的檔案,因此,也稱為偽target(phony target)。
dependencies是生成target所需的檔名列表。依賴可以為空,常用的“clean”target就常常沒有依賴,只有命令。
命令可以是任何一個shell能執行的命令。
2、makefile示例
我們先以“hello,world”為例,說明makefile的使用。在linux的shell環境中用vim編譯hello.c
[email protected]:~/2$ vim hello.c
在開啟的VIM視窗中進行編輯。
#include <stdio.h>
int main(void)
{
printf ("hello,world!");
return 0;
}
然後編譯,這次一步到位編譯完成
[email protected]:~/2$ gcc hello.c -o hello [email protected]:~/2$ ./hello hello,world!
接著編寫makefile檔案,實現hello程式的編譯自動化。Makefile檔案內容如下:
hello:hello.c
gcc hello.c -o hello
clean:
rm hello
上面程式碼中,clean後沒有被依賴的檔案,因此,不會被make自動執行,這種情況可理解為一種命令。
make依賴關係檢查系統非常簡單,主要根據依賴檔案的修改時間進行判斷,如果時間比編譯時的時間要新,才重新編譯,否則不會重新,如果需要呼叫make強行重新編譯,就需要將編譯後的目標檔案刪除。因此這裡定義了clean,當想重新呼叫make編譯hello.c時,可以主動呼叫make clean來清除編譯。
我們編譯,執行後,再使用clean選項清除目標檔案,重新編譯一次。
[email protected]:~/2$ make
gcc hello.c -o hello
[email protected]:~/2$ ./hello
hello,world!
[email protected]:~/2$ make clean
rm hello
[email protected]:~/2$ make
gcc hello.c -o hello
[email protected]:~/2$