How to write Makefile

Posted on 2018-10-06

How to write Makefile

Start from an example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
DTR_URL ?= dockerhub.paypalcorp.com
DTR_USER ?= $USER
DTR_REPO ?= cassandra
VERSIONS ?= 2.1 2.2 3.0 3.11
BUILD_VERSIONS = $(addprefix build-, $(VERSIONS))
PUSH_VERSIONS = $(addprefix push-, $(VERSIONS))

.PHONY: build push

# TODO: should add flag to allow ignore cache when build
build: $(BUILD_VERSIONS)
push: $(PUSH_VERSIONS)

# NOTE: (piguo), I know addprefix and remove them is ugly, if you know a better way, please tell me.
$(BUILD_VERSIONS):
$(eval VER=$(subst build-,,$@)) cd $(VER) && docker build -t $(DTR_URL)/$(DTR_USER)/$(DTR_REPO):$(VER) .

$(PUSH_VERSIONS):
$(eval VER=$(subst push-,,$@)) docker push $(DTR_URL)/$(DTR_USER)/$(DTR_REPO):$(VER)%
1
DTR_URL ?= dockerhub.paypalcorp.com

?表示,如果这个env variables没有设置,才设置为dockerhub.paypalcorp.com

Functions for transforming text

1
BUILD_VERSIONS = $(addprefix build-, $(VERSIONS))

形式为:

1
$(function arguments)

常见的function有:

  • $(subst from,to,text), 字符替换
    foo:= a b c
    bar:= $(subst $(space),$(comma),$(foo))
    # bar is nowa,b,c’.`
  • $(strip string), 去除leading和tail的空格。并且把字符串内部的1个和多个空格全部替换成单个空格。例如”a b” to “a b”

.PHONY

PHONY 目标并非实际的文件名:只是在显式请求时执行命令的名字。
好处:avoid a conflict with a file of the same name, and to improve performance.
eg: make clean, 如果当前的folder下也有一个名为clean的文件,那么命令失效。