本文並非Makefile的教程,僅是本人學習時的感悟。shell
Makefile的基本格式bash
目標:依賴文件(or 目標) [tab]命令
目標: 是要生成的或操做的命令的索引
依賴: 是生成目標依賴的文件或目標
命令: 是爲了生成目標須要執行的shell語句學習
任意一個依賴文件被改動,將致使已存在的目標文件過時,簡單來講,依賴的做用就是決定目標是否過時,是否須要從新編譯。code
舉個例子,教程
#include <stdio.h> #include "mylib1.h" #include "mylib2.h" int main(int argc, char argv[]){ printf("hello world!\n"); }
對應的Makefile能夠是索引
helloworld: stdio.h mylib1.h mylib2.h other.o gcc -o helloworld helloworld.c
也能夠是get
helloworld: other.o gcc -o helloworld helloworld.c
前者但願在stdio.h、mylib1.h、mylib2.h、other.o被修改時從新執行helloworld目標,然後者僅僅但願檢查other.o的修改。io
目標依賴每每還有另一種用法,用於執行其餘目標。例如編譯
.PHONY: all clean target all: target clean target: helloworld.o gcc helloworld.o -o helloworld helloworld.o: gcc -c helloworld.c clean: rm helloworld.o
執行all
目標的時候,依賴另外兩個目標target
和clean
。在執行all
目標前,會優先執行目標target
和clean
。class
怎麼判斷all
依賴的是目標仍是文件?
.PHONY: all all: test @echo in all test: @echo in test
執行這個Makefile時,當前目錄下有無test文件會有兩個不一樣的執行結果
[GMPY@11:24 tmp]$ll 總用量 4.0K 1186807 -rw-r--r-- 1 gmpy gmpy 57 4月 5 11:20 Makefile [GMPY@11:24 tmp]$make echo in test in test echo in all in all [GMPY@11:24 tmp]$touch test #建立test文件 [GMPY@11:24 tmp]$make echo in all in all [GMPY@11:24 tmp]$
總結來講,判斷依賴是目標仍是文件,有如下兩個規則: