Go语言交叉编译

简介

go 可以在一个平台上编译其他平台的可执行文件,称为交叉编译

交叉编译

使用交叉编译只需要设置以下几步

  • 设置 CGO_ENABLED 为 0
  • 设置 GOOS 环境变量,选择你的目标操作系统
  • 设置 GOARCH 环境变量,选择你的目标 CPU 架构

Windows 下编译

编译为 windows amd64

1
2
3
4
set CGO_ENABLED=0
set GOOS=windows
set GOARCH=amd64
go build

编译为 windows arm64

1
2
3
4
set CGO_ENABLED=0
set GOOS=windows
set GOARCH=arm64
go build

编译为 linux amd64

1
2
3
4
set CGO_ENABLED=0
set GOOS=linux
set GOARCH=amd64
go build

案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Define configuration file and extract app name/version
APP_CONFIG_FILE := ./config/config.toml
APP_NAME := $(shell sed -n 's/^name = "\(.*\)"/\1/p' < $(APP_CONFIG_FILE))
APP_VERSION := $(shell sed -n 's/^version = "\(.*\)"/\1/p' < $(APP_CONFIG_FILE))

# Build directory
BUILD_DIR := ./build

# Supported platforms
PLATFORMS := windows-amd64 linux-amd64 darwin-amd64

# Platform-specific suffixes
WINDOWS_SUFFIX := .exe
DEFAULT_SUFFIX :=

# Clean build artifacts
clean:
	go clean
	rm -rf $(BUILD_DIR)

# Build for all platforms
build:
	@mkdir -p $(BUILD_DIR)
	@for platform in $(PLATFORMS); do \
		os=$$(echo $$platform | cut -d '-' -f 1); \
		arch=$$(echo $$platform | cut -d '-' -f 2); \
		suffix=$$DEFAULT_SUFFIX; \
		if [ "$$os" = "windows" ]; then \
			suffix=$(WINDOWS_SUFFIX); \
		fi; \
		echo "Building for GOOS=$$os GOARCH=$$arch platform=$$platform with suffix $$suffix"; \
		GOOS=$$os GOARCH=$$arch go build -o $(BUILD_DIR)/$(APP_NAME)-$(APP_VERSION)-$$platform$$suffix main.go; \
	done

# Default target
all: clean build

执行如下命令编译

1
make all

附录

GOOS 和 GOARCH 可选值对应表

$GOOS $GOARCH
aix ppc64
android 386
android amd64
android arm
android arm64
darwin amd64
darwin arm64
dragonfly amd64
freebsd 386
freebsd amd64
freebsd arm
illumos amd64
ios arm64
js wasm
linux 386
linux amd64
linux arm
linux arm64
linux loong64
linux mips
linux mipsle
linux mips64
linux mips64le
linux ppc64
linux ppc64le
linux riscv64
linux s390x
netbsd 386
netbsd amd64
netbsd arm
openbsd 386
openbsd amd64
openbsd arm
openbsd arm64
plan9 386
plan9 amd64
plan9 arm
solaris amd64
wasip1 wasm
windows 386
windows amd64
windows arm
windows arm64

参考:https://go.dev/doc/install/source#environment

页面浏览量Loading
网站总访客数:Loading
网站总访问量:Loading
使用 Hugo 构建
主题 StackJimmy 设计
-->