NotePublic/Software/Development/Language/Go/Basic/Go_交叉编译.md

55 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Go 交叉编译
Golang 的交叉编译是通过设置编译宏变量来实现的,主要是 GOOS 和 GOARCH列表如下
| GOOS - Target Operating System | GOARCH - Target Platform |
|--------------------------------|--------------------------|
| android | arm |
| android | arm64 |
| android | 386 |
| android | amd64 |
| darwin | 386 |
| darwin | amd64 |
| darwin | arm |
| darwin | arm64 |
| dragonfly | amd64 |
| freebsd | 386 |
| freebsd | amd64 |
| freebsd | arm |
| linux | 386 |
| linux | amd64 |
| linux | arm |
| linux | arm64 |
| linux | ppc64 |
| linux | ppc64le |
| linux | mips |
| linux | mipsle |
| linux | mips64 |
| linux | mips64le |
| netbsd | netbsd |
| netbsd | amd64 |
| netbsd | arm |
| openbsd | 386 |
| openbsd | amd64 |
| openbsd | arm |
| plan9 | 386 |
| plan9 | 386 |
| solaris | amd64 |
| windows | 386 |
| windows | amd64 |
使用示例如下:
```bash
GOOS=linux GOARCH=arm64 go build
```
交叉编译是不支持 CGO 的,也就是说如果你的代码中存在 C 代码,是编译不了的。,比如说你的程序中使用了 sqlite 数据库,在编译 go-sqlite 驱动时按照上面的做法是编译不通过的。
需要 CGO 支持的,要将 CGO_ENABLED 的 0 改为 1也就是“CGO_ENABLED=1”此外还需要设置编译器例如我想在 linux 上编译 arm 版的二进制,需要这样做:
```bash
# Build for arm
CGO_ENABLED=1 GOOS=linux GOARCH=arm CC=arm-linux-gnueabi-gcc go build
```