Why Makefile/GNU Make?

  • macOS 和 Linux 內建
  • 方便執行重複性工作

開始使用

  • 建立一個名為 Makefile 的檔案
  • 必須使用 tab 縮排
Makefile
hello:
	echo "Hello, World!"
 
world:
	echo "World Hello!"
$ make hello
# echo "Hello, World!"
# Hello, World!

Glossary

  • Rule: 上述 Makefile 包含兩個 Rule
  • Target: 也就是上述的 helloworld。target 預設是檔案名稱,但也可以是 phony target
  • Recipe: make 會執行的動作/指令,也就是上述的 echo "Hello, World!"。可以為多行,直到空白行之前都是同一個 target 的 recipe
  • Goal: Makefile 中第一個 target,以上述來說執行 make 和執行 make hello 是一樣的結果

進入 Makefile 的世界

Makefile 顧名思義,是用來「創造檔案」的工具,所有思路都是圍繞著「目標檔案」在進行的。基本的 Makefile Rule 結構如下:

targets: prerequisites [; recipe]
    recipe
    ...
    ...

Prerequisites

Prerequisite Types (GNU make)

中文直譯是「先決條件」,也就是要產生當前 target 所需要的 input。當 prerequisites 中的檔案不存在時,會依序執行 prerequisites target 的 recipe,最後才執行目前 target 的 recipe。

Phony Targets

Phony Targets (GNU make)

Makefile教學: 一篇文章教會妳Phony

只會執行指定動作,不與檔案有關的 target 稱為 phony target。這種 traget 不含有 prerequisites。 例如常見的 clean target:

.PHONY: clean
clean:
	rm -rf *.o temp

Variables

How to Use Variables (GNU make)

Directive

4.5.2 The vpath Directive 6.7 The override Directive 12.2.1 The load Directive

Functions

Functions for Transforming Text (GNU make)


參考資料
延伸閱讀