Golang:交叉编译到Linux、macOS、windows并运行

时间:2023-02-12 13:57:36

Golang可以直接编译成不同平台的可执行文件,并且直接运行,很方便第三方使用者部署运行

项目结构

$ tree
.
├── Makefile
└── src
    └── hello.go

项目很简单,一个Hello 程序,仅为了演示打包到不同平台并执行的效果 hello.go

package main

import "fmt"

func main() {
    fmt.Printf("hello\n")
}

为了简化命令行编写,采用Makefile 文件整合命令

Makefile


# 编译到 Linux
.PHONY: build-linux
build-linux:
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ./build/hello-linux ./src/hello.go 

# 编译到 macOS
.PHONY: build-darwin
build-darwin:
    CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o ./build/hello-darwin ./src/hello.go

# 编译到 windows
.PHONY: build-windows
build-windows:
    CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o ./build/hello-windows.exe ./src/hello.go 

# 编译到 全部平台
.PHONY: build-all
build-all:
    make clean
    mkdir -p ./build
    make build-linux
    make build-darwin
    make build-windows

.PHONY: clean
clean:
    rm -rf ./build

编译成可执行文件

运行编译命令

$ make build-all

$ ls -lh ./build/

1.8M  2 12 13:05 hello-darwin
1.7M  2 12 13:05 hello-linux
1.9M  2 12 13:05 hello-windows.exe

可以看到,生成了三个平台的可执行文件,平均大小1.8M

运行测试

分别到三个平台执行

1、Mac OS

$ sw_vers 
ProductName:    Mac OS X
ProductVersion: 10.14.4
BuildVersion:   18E2035

$ ./hello-darwin
hello

2、Linux

$ cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)

$ ./hello-linux
hello

3、Windows (终端使用MINGW64)

$ systeminfo
OS Name:    Microsoft Windows 10 专业版
OS Version: 10.0.19045 N/A Build 19045

$ ./hello-windows.exe
hello

查看支持的平台

$ go tool dist list
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
illumos/amd64
ios/amd64
ios/arm64
js/wasm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/loong64
linux/mips
linux/mips64
linux/mips64le
linux/mipsle
linux/ppc64
linux/ppc64le
linux/riscv64
linux/s390x
netbsd/386
netbsd/amd64
netbsd/arm
netbsd/arm64
openbsd/386
openbsd/amd64
openbsd/arm
openbsd/arm64
openbsd/mips64
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
windows/386
windows/amd64
windows/arm
windows/arm64

参考 Golang 在 Mac、Linux、Windows 下如何交叉编译