运行 make windows、make linux 和 make darwin,分别构建 windows、linux 和 drawin 操作系统的可执行文件。
运行结果如下:
.
├── Makefile
├── blog
├── blog-darwin
├── blog-linux
├── blog-windows
├── go.mod
└── main.go
需要注意的是,如果有文件名和“伪目标”同名,那么该“伪目标”无法使用 make 命令执行指定的 command。因为 make 发现与“伪目标”同名的文件已存在,将不会再重新构建,所以就不会运行指定的 command,为了避免出现该问题,可以使用内置目标名.PHONY声明这些“伪目标”名是“伪目标”,而不是与“伪目标”同名的文件。
完整 Makefile 文件:
APP=blog
.PHONY: help all build windows linux darwin
help:
@echo "usage: make
@echo "options and effects:"
@echo " help : Show help"
@echo " all : Build multiple binary of this project"
@echo " build : Build the binary of this project for current platform"
@echo " windows: Build the windows binary of this project"
@echo " linux : Build the linux binary of this project"
@echo " darwin : Build the darwin binary of this project"
all:build windows linux darwin
build:
@go build -o ${APP}
windows:
@GOOS=windows go build -o ${APP}-windows
linux:
@GOOS=linux go build -o ${APP}-linux
darwin:
@GOOS=darwin go build -o ${APP}-darwin
阅读上面示例代码,我们可以看到 Makefile 中第二个“伪目标” all,该目标只有 4 个先决条件,没有任何命令。执行 make all 命令,可以批量执行多个“伪目标”。该命令等同于以下命令: