使用 Makefile
做自动化编译.
Makefile 示例
.PHONY : build prod package modules version
BUILD_FLAGS = CGO_ENABLED=0 GOOS=linux GOARCH=amd64
BUILD_OBJECT = toolman
GO = go
VERSION = $(shell git tag --sort=committerdate | tail -n 1)
COMPRESS_OBJECT = $(BUILD_OBJECT)-$(VERSION).tar.gz
COMPRESS_FILES = ${BUILD_OBJECT} template
build : modules main.go
$(BUILD_FLAGS) $(GO) build -o $(BUILD_OBJECT) main.go
prod : version build
package : prod
tar -zcf $(COMPRESS_OBJECT) $(COMPRESS_FILES)
modules : go.mod
$(GO) mod download
version :
sed -i "s/version = \".*\"/version = \"$(VERSION)\"/g" cmd/version.go
规则
target ... : prerequisites ...
command
...
...
target
可以是一个 object file
(目标文件), 也可以是一个执行文件, 还可以是一个标签 (label, 伪目标).
例如: build
.
prerequisites
生成 target
所依赖的文件 或 target
例如: go.mod
作为 modules
的 依赖文件; modules
作为 build
的 依赖 target
.
command
target
要执行的命令 (任意的 shell
命令)
伪目标
.PHONY : version
只要有这个声明,不管是否有 version
文件, make version
总会执行对应的命令.
变量
定义变量
BUILD_FLAGS = CGO_ENABLED=0 GOOS=linux GOARCH=amd64
BUILD_OBJECT = toolman
GO = go
VERSION = $(shell git tag --sort=committerdate | tail -n 1)
COMPRESS_OBJECT = $(BUILD_OBJECT)-$(VERSION).tar.gz
COMPRESS_FILES = ${BUILD_OBJECT} template
使用变量
build : modules main.go
$(BUILD_FLAGS) $(GO) build -o $(BUILD_OBJECT) main.go
prod : version build
package : prod
tar -zcf $(COMPRESS_OBJECT) $(COMPRESS_FILES)
modules : go.mod
$(GO) mod download
version :
sed -i "s/version = \".*\"/version = \"$(VERSION)\"/g" cmd/version.go
运行
运行第一个 target
make
运行指定的 target
make build