How to cross compile golang on different platforms

Time:2021-7-6

Golang supports cross compilation. It can generate executable programs on one platform and on another platform. Recently, it has been used, which is very easy to use. Here is a note.

Parameter description

  • Goos: operating system of target platform (Darwin, FreeBSD, Linux, windows)
  • Goarch: architecture of target platform (386, AMD64, arm)
  • CGO_ENABLED : Cross compilation does not support CGO, so disable it

Compiling Linux and windows 64 bit executable program under mac

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

Compiling Mac and windows 64 bit executable program under Linux

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

Compiling 64 bit executable program of MAC and Linux 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

The above command compiles 64 bit executable programs. Of course, you should also use 386 to compile 32-bit executable programs

This work adoptsCC agreementReprint must indicate the author and the link of this article

golang