我在 Windows 10 上安装了 GO 1.7。我创建了测试程序,它在 Windows 中运行良好。下一步是尝试使用 Ubuntu 在我的 docker 虚拟机上运行它。
我找到了 here关于如何做的一些信息
set GOARCH=amd64
set GOOS=linux
go tool dist install -v pkg/runtime
go install -v -a std
我在cmd中运行第1行和第2行没有问题。在第 3 行我有一个错误
go tool dist: open C:\Go\src\pkg\runtime: The system cannot find the path specified.
我手动检查了这个文件夹,有一个只适用于 windows 的运行时
问题是我可以在哪里以及如何为 Linux 下载它?或者也许我正在做的是完全错误的方式......
2017 年 9 月 2 日更新
我按照建议跑了
set GOARCH=amd64
set GOOS=linux
go build -o "myapp"
在我将此文件复制到共享文件夹后,从那里复制到另一个非共享文件夹(以避免描述 here 的问题)并执行
root@7dd1655ae5db:/__notshared# ./myapp
bash: ./myapp: cannot execute binary file: Exec format error
下载文件包后检查我的文件
root@7dd1655ae5db:/__notshared# file myapp
myapp: PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows
似乎在构建期间没有创建 linux 可执行文件。
最佳答案
另一个问题有点老(从 2013 年开始)。
跨平台支持发展了很多,您需要做的就是更改环境变量(GOARCH
和 GOOS
)并运行 go build
.
导航到 main
包的文件夹,然后:
set GOARCH=amd64
set GOOS=linux
go build
您可以像这样更改结果二进制文件的名称:
go build -o "myapp"
请注意,在 Linux 中为 Windows amd64 编译应用程序,一条命令就足够了(在 main
包的文件夹中):
GOOS=windows GOARCH=amd64 go build
这也在博文中得到证实:Dave Cheney: Cross compilation with Go 1.5 :
To cross compile a Go program using Go 1.5 the process is as follows:
set
GOOS
andGOARCH
to be the values for the target operating system and architecture.run
go build -v YOURPACKAGE
注意事项
您不必,也不应该运行 go install
,因为这会编译并安装您的 GOPATH
中的包,这通常是不需要的.进行交叉编译不是为了开发/测试您的应用程序和包。它是为了生成一个二进制文件,您将在另一个系统/计算机上运行它。
go build
不会安装任何东西,它只会生成可执行二进制文件。有关详细信息,请参阅 What does go build build?
也在博文中确认:Dave Cheney: Cross compilation with Go 1.5 :
When cross compiling, you should use
go build
, notgo install
. This is the one of the few cases wherego build
is preferable togo install
.The reason for this is
go install
always caches compiled packages,.a
files, into thepkg/
directory that matches the root of the source code.
关于Go 1.7 从 Windows 到 Linux/Ubuntu 的交叉编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117934/