閱讀《跟我一塊兒寫makefile》,摘錄文章我的認爲有助於理解的語句,並記錄本身驗證明踐的過程,方便本身後續工做中複習。bash
target ... : prerequisites ... command測試
這是一個文件的依賴關係,也就是說,target 這一個或多個的目標文件依賴於prerequisites 中的文件,其生成規則定義在 command 中。說白一點就是說,prerequisites中若是有一個以上的文件比 target 文件要新的話,command 所定義的命令就會被執行。這就是 Makefile 的規則。也就是 Makefile 中最核心的內容。ui
顯式規則,依賴關係寫的比較清楚。spa
run: main.o hello.o test.o
gcc -o run main.o hello.o test.o
main.o: main.c
gcc -c main.c
hello.o: hello.c
gcc -c hello.c
test.o: test.c
gcc -c test.c
clean:
rm run *.o
複製代碼
運行結果:code
root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make run
gcc -c main.c
gcc -c hello.c
gcc -c test.c
gcc -o run main.o hello.o test.o
複製代碼
run所須要的依賴文件不存在時,執行下一語句。待依賴文件生成時,繼續執行run對應的命令。get
若是依賴的test.o文件沒有生成的規則,makefile會自動產生規則去生成test.o文件。這個特性就是隱晦規則,主要靠make自動推導。只要 make 看到一個[.o]文件,它就會自動的把[.c]文件加在依賴關係中,如自動把test.c加入到依賴關係中,而且cc -c -o test.o test.c也會被推導出來。源碼
刪除該語句測試
test.o: test.c
gcc -c test.c
複製代碼
運行結果:string
gcc -c main.c
gcc -c hello.c
cc -c -o test.o test.c
gcc -o run main.o hello.o test.o
複製代碼
若是沒有test.c文件則沒法生成,直接終止執行。it
root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make run
gcc -c main.c
gcc -c hello.c
make: *** No rule to make target `test.o', needed by `run'. Stop.
複製代碼
make 並無論命令是怎麼工做的,他只管執行所定義的命令。 make 會比較 targets 文件和 prerequisites 文件的修改日期,若是 prerequisites 文件的日期要比 targets 文件的日期要新,或者 target 不存在的話,那麼,make 就會執行後續定義的命令。我發覺書上這句話有點問題。 測試把hello.c文件刪除後,即沒法生成hello.o這個target,執行make run,結果以下編譯
root@chenwr-pc:/home/workspace/my_workspace/study/makefile# make run
gcc -c main.c
make: *** No rule to make target `hello.c', needed by `hello.o'. Stop.
複製代碼
後續定義的語句並不會去執行,直接終止。
test.o: test.c
gcc -c test.c
複製代碼
原來是我理解錯誤了,書中後面提到: 在找尋的過程當中,若是出現錯誤,好比最後被依賴的文件找不到,那麼make 就會直接退出,並報錯,而對於所定義的命令的錯誤,或是編譯不成功,make 根本不理。make 只管文件的依賴性,即,若是在我找了依賴關係以後,冒號後面的文件仍是不在,那麼對不起,我就不工做啦。 這個target不存在,是指上一次編譯生成的run,已經不存在須要執行對應的command來產生。而且大前提是整個makefile的依賴關係正確和編譯命令所需的文件是存在的狀況下。