4

交叉编译Go程序

 2 years ago
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.
neoserver,ios ssh client

交叉编译 Go 程序

发表于 2017-05-12 更新于 2021-12-02 分类于 go 阅读次数:380 Disqus: 本文字数: 1.1k 阅读时长 ≈ 2 分钟

你只需设置 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$GOARCHdarwin386darwinamd64darwinarmdarwinarm64dragonflyamd64freebsd386freebsdamd64freebsdarmlinux386linuxamd64linuxarmlinuxarm64linuxppc64linuxppc64lenetbsd386netbsdamd64netbsdarmopenbsd386openbsdamd64openbsdarmplan9386plan9amd64solarisamd64windows386windowsamd64

不同的操作系统下的库可能有不同的实现, 比如 syscall 库。go build 没有内置的#define 或者预处理器之类的处理平台相关的代码取舍, 而是采用 tag 和文件后缀的方式实现。
tag 方式
tag 遵循一下规则

  1. a build tag is evaluated as the OR of space-separated options
  2. each option evaluates as the AND of its comma-separated terms
  3. 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 等。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK