交叉编译Go程序
source link: https://www.purewhite.io/2017/05/12/go-cross-compile/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
交叉编译 Go 程序
你只需设置 GOOS 和 **GOARCH ** 两个环境变量就能生成所需平台的 Go 程序。
比如使用下面的代码测试:
package main
import "fmt"
import "runtime"
func main() {
fmt.Printf("OS: %s\nArchitecture: %s\n", runtime.GOOS, runtime.GOARCH)
}
编译它: $ GOOS=darwin GOARCH=386 go build test.go
就可以生成运行在 OS X
上的程序。
可用的 OS 和 ARCH 的值如下:
$GOOS
$GOARCH
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
netbsd
386
netbsd
amd64
netbsd
arm
openbsd
386
openbsd
amd64
openbsd
arm
plan9
386
plan9
amd64
solaris
amd64
windows
386
windows
amd64
不同的操作系统下的库可能有不同的实现, 比如 syscall 库。go build 没有内置的#define
或者预处理器之类的处理平台相关的代码取舍, 而是采用 tag 和文件后缀的方式实现。
tag 方式
tag 遵循一下规则
- a build tag is evaluated as the OR of space-separated options
- each option evaluates as the AND of its comma-separated terms
- each term is an alphanumeric word or, preceded by !, its negation
在文件的头部增加 tag:
// +build darwin freebsd netbsd openbsd
可以有多个 tag, 之间是 AND 的关系
// +build linux darwin
// +build 386
注意 tag 和 package 中间需要有空行分隔,下面的例子是不对的:
// +build !linux
package mypkg // wrong
文件后缀方式
以 *_$GOOS.go * 为后缀的文件只在此平台上编译,其它平台上编译时就当此文件不存在。完整的后缀如:
_$GOOS_$GOARCH.go
如 syscall_linux_amd64.go,syscall_windows_386.go,syscall_windows.go 等。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK