Detailed explanation of cross compilation in Golang

Cross compilation in Golang

In Golang, cross-compilation refers to generating binaries for different operating systems or hardware architectures on the same machine. This is useful when developing cross-platform apps or building platform-specific releases.

The basic steps to cross-compile a Golang program are as follows:

  1. Specify the target operating system and toolchain and set the corresponding environment variables

When compiling, you need to specify the target operating system and toolchain. This can be done by setting the GOOS and GOARCH environment variables. For example, if you want to compile an ARM program for Linux, you can set the following environment variables:

GOOS=linux  
GOARCH=arm
  1. Enter the source code directory to execute the compile command

Before starting to compile, you need to switch to the directory containing the source code and use the go build command to compile the program.

cross compile on mac

# 编译出可以在 Windows 中运行的二进制文件
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

# 编译出可以在 Linux 中运行的二进制文件
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go

Cross compile on Linux

# 编译出可以在 Windows 中运行的二进制文件
CGO_ENABLED=0 GOOS=windows  GOARCH=amd64  go build main.go

# 编译出可以在 mac 中运行的二进制文件
CGO_ENABLED=0 GOOS=darwin  GOARCH=amd64  go build main.go

Cross compile on Windows

Windows is a bit different from Mac and Linux. It can be done by writing a batch program. The compilation environment for compiling binary files that can run on Mac is set as follows:

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

Set up the compilation environment to compile binary files that can run in Linux as follows:

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

The meanings of the environment variables in the above examples are as follows:

  • CGO_ENABLED: CGO_ENABLED=0 means to disable CGO, because cross-compilation cannot enable CGO.
  • GOOS: Indicates the target platform, for example, mac system corresponds to darwin, linux system corresponds to linux, windows system corresponds to windows, etc.
  • GOARCH: The architecture of the target platform, such as amd64, arm, etc.

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/132240271