makefile 描述了整個工程的編譯,鏈接過程。我們知道生成可執行文件的過程爲 源文件--->.o文件-->可執行文件。源文件可能有多個文件,對應生成多個對象文件(。o文件),要生成可執行文件需要將這些對象文件進行鏈接。以下爲一個makefile文件:
hello: main.o func1.o func2.o
gcc main.o func1.o func2.o -o hello
main.o : main.c
gcc –c main.c
func1.o : func1.c
gcc –c func1.c
func2.o : func2.c
gcc –c func2.c
.PHONY : clean
clean :
rm –f hello main.o func1.o func2.o
makefile的規制爲:
targets:prerequisites
command
目標:依賴
命令
第一行和第二行的代碼對應生成 最終目標hello,怎麼生成hello呢,對應的依賴爲幾個目標文件main.o,func1.o,func2.o。使用的命令爲gcc main.o func1.o func2.o -o hello
注意,命令這行需要以“TAB”鍵開始,即前面的空白不是按空格鍵形成的。後面幾行代碼對應生成。o文件的代碼。
Makefile中把那些沒有任何依賴只有執行動作的目標稱爲“僞目標”(phony targets)。
.PHONY : clean
clean :
rm –f hello main.o func1.o func2.o
“.PHONY” 將“clean”目標聲明爲僞目標
寫完makefile後使用make命令即可完成編譯和鏈接工作。make命令默認在當前目錄下尋找名字爲makefile或者Makefile的工程文件,當名字不爲這兩者之一時,可以使用如下方法指定:
make –f 文件名
當執行上面的makefile程序時我們發現目標文件。o並沒有被刪除掉,爲什麼呢?因爲直接使用make命令只生成了第一個目標,而僞目標clean並沒有執行。只要執行make clean 命令就能執行makefile的clean目標。
思考:如果要爲hello目標添加一個依賴,如:func3.o,該如何修改?
答案1:
hello: main.o func1.o func2.o func3.o
gcc main.o func1.o func2.o func3.o -o hello
答案2:
obj=main.o func1.o func2.o func3.o
hello: $(obj)
gcc $(obj) -o hello
通過變量的方法來更改相關設定