咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Golang交叉编译

本文以Windows平台下编译Linux应用举例,记录一下Golang交叉编译。

1
2
3
4
5
6
7
8
# help
go get:获取远程包(需 提前安装 git或hg)
go run:直接运行程序
go build:测试编译,检查是否有编译错误
go fmt:格式化源码(部分IDE在保存时自动调用)
go install:编译包文件并编译整个程序
go test:运行测试文件
go doc:查看文档(CHM手册)

一、设置环境变量

1
2
$ set GOARCH=amd64
$ set GOOS=linux

在终端CMD输入没用,我直接在环境变量设置了 GOARCHGOOS 。这样就无法在Windows运行,因为 go run 的也是指linux平台。

二、编译

1
$ go build xx.go

三、依赖错误

编译的时候,出现 unrecognized import path "golang.org/x/sys/unix" 错误,本来就是下载依赖库网络超时,但科学上网也没有解决。

在Ubuntu下编译也会出现这个错误

详细错误信息:

1
2
3
4
5
6
Fetching https://golang.org/x/sys/unix?go-get=1
https fetch failed: Get https://golang.org/x/sys/unix?go-get=1:
dial tcp 216.239.37.1:443: i/o timeout
package golang.org/x/sys/unix: unrecognized import path "golang.org/x/sys/unix"
(https fetch: Get https://golang.org/x/sys/unix?go-get=1:
dial tcp 216.239.37.1:443: i/o timeout)

解决办法: 通过手动下载Github上的3个依赖项目到 $GOPATH/src/golang.org/x/ 目录

  • github.com/golang/net.git
  • github.com/golang/sys.git
  • github.com/golang/tools.git

以下是在Linux的操作日志(Windows也是通过的办法):

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
root@ubuntu:~/golangworks/src$ mkdir -p $GOPATH/src/golang.org/x/
root@ubuntu:~/golangworks/src$ cd !$
cd $GOPATH/src/golang.org/x/
root@ubuntu:~/golangworks/src/golang.org/x$ git clone https://github.com/golang/net.git
Cloning into 'net'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 8766 (delta 0), reused 1 (delta 0), pack-reused 8762
Receiving objects: 100% (8766/8766), 6.77 MiB | 601.00 KiB/s, done.
Resolving deltas: 100% (6184/6184), done.
root@ubuntu:~/golangworks/src/golang.org/x$ git clone https://github.com/golang/sys.git
Cloning into 'sys'...
remote: Enumerating objects: 8003, done.
remote: Total 8003 (delta 0), reused 0 (delta 0), pack-reused 8003
Receiving objects: 100% (8003/8003), 6.28 MiB | 554.00 KiB/s, done.
Resolving deltas: 100% (6884/6884), done.
root@ubuntu:~/golangworks/src/golang.org/x$ git clone https://github.com/golang/tools.git
Cloning into 'tools'...
remote: Enumerating objects: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 29602 (delta 0), reused 1 (delta 0), pack-reused 29596
Receiving objects: 100% (29602/29602), 13.76 MiB | 1.29 MiB/s, done.
Resolving deltas: 100% (20632/20632), done.

四、平台

1.GOOS:目标平台的操作系统

  • windows
  • linux
  • darwin (MacOX)
  • freebsd

2.GOARCH:目标平台的体系架构

  • 386 (32位x86)
  • amd64 (64位x86)
  • arm