Makefile示例

首页 编程分享 LINUX丨SYSTEM 正文

anonymous 转载 编程分享 2020-12-26 22:35:06

简介 使用 Makefile 做自动化编译. Makefile 示例 .PHONY : build prod package modules version BUILD_...


使用 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

原文链接: https://goworker.cn/posts/hello-makefile/

转载链接:https://my.oschina.net/k8scat/blog/4819575


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云