Golang – Go build 编译成不同环境的可执行文件mac、linux、windows

解决Golang的多端编译

一个特别方便的东东就可以忽略下面的了。

https://github.com/mitchellh/gox

$ go install github.com/mitchellh/gox@latest
...
$ gox -h
...
$ gox
Number of parallel builds: 4

-->      darwin/386: github.com/mitchellh/gox
-->    darwin/amd64: github.com/mitchellh/gox
-->       linux/386: github.com/mitchellh/gox
-->     linux/amd64: github.com/mitchellh/gox
-->       linux/arm: github.com/mitchellh/gox
-->     freebsd/386: github.com/mitchellh/gox
-->   freebsd/amd64: github.com/mitchellh/gox
-->     openbsd/386: github.com/mitchellh/gox
-->   openbsd/amd64: github.com/mitchellh/gox
-->     windows/386: github.com/mitchellh/gox
-->   windows/amd64: github.com/mitchellh/gox
-->     freebsd/arm: github.com/mitchellh/gox
-->      netbsd/386: github.com/mitchellh/gox
-->    netbsd/amd64: github.com/mitchellh/gox
-->      netbsd/arm: github.com/mitchellh/gox
-->       plan9/386: github.com/mitchellh/gox

Or, if you want to build a package and sub-packages:

$ gox ./...
...

Or, if you want to build multiple distinct packages:

$ gox github.com/mitchellh/gox github.com/hashicorp/serf
...

Or if you want to just build for linux:

$ gox -os="linux"
...

Or maybe you just want to build for 64-bit linux:

$ gox -osarch="linux/amd64"
...

And more! Just run gox -h for help and additional information.

1、Mac下编译Linux, Windows平台的64位可执行程序:

$ go env -w CGO_ENABLED=0 GOOS=linux GOARCH=amd64 
$ go env -w CGO_ENABLED=0 GOOS=windows GOARCH=amd64

2、Linux下编译Mac, Windows平台的64位可执行程序:

$ go env -w CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 
$ go env -w CGO_ENABLED=0 GOOS=windows GOARCH=amd64

3、Windows下编译Mac, Linux平台的64位可执行程序:

$ go env -w CGO_ENABLED=0 GOOS=darwin3 GOARCH=amd64 
$ go env -w CGO_ENABLED=0 GOOS=linux GOARCH=amd64

4、开始编译

go build -o "存储编译后的目录,默认当前目录" main.go