How to cross compile Golang under Mac, Linux, Windows

Golang supports cross-compilation, generating executable programs on one platform for another platform.

Compile Linux and Windows 64-bit executables under Mac

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Compile Mac and Windows 64-bit executables under Linux

CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Compile Mac and Linux 64-bit executables under Windows

SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go

SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go

GOOS: The operating system of the target platform (darwin, freebsd, linux, windows)
GOARCH: The architecture of the target platform (386, amd64, arm)
Cross-compilation does not support CGO so disable it

The above command compiles 64-bit executable programs, of course, you should also use 386 to compile 32-bit executable programs
Many blogs mention that support for other platforms must be added first, but I skip that step, and the commands listed above also All succeed and get the results I want. It can be seen that that step should be optional, or the version of Go I am using already supports all platforms by default.

illustrate

Powershell does not work under windows, you need cmd

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812977&siteId=291194637
Recommended