golang 跨平台编译——go 在windows上编译Linux平台的程序(Cross Compilation from Windows to Linux/Ubuntu)

Go Cross Compilation from Windows to Linux/Ubuntu

 I have GO 1.7 installed on my Windows 10. I created test program and it works perfectly in Windows. Next step is to try to run it on my docker virtual machine with Ubuntu.

 

Answer:

That other question is a bit old (from 2013).

Cross-platform support evolved a lot, all you need to do is change the environment variables (GOARCH and GOOS) and run go build.

Navigate to the folder of the main package, then:

set GOARCH=amd64
set GOOS=linux
go build

You may change the name of the result binary like this:

go build -o "myapp"

Note that in Linux to compile the app for Windows amd64, a single command is enough (in the folder of the main package):

GOOS=windows GOARCH=amd64 go build

This is also confirmed in blog post: Dave Cheney: Cross compilation with Go 1.5:

To cross compile a Go program using Go 1.5 the process is as follows:

  1. set GOOS and GOARCH to be the values for the target operating system and architecture.

  2. run go build -v YOURPACKAGE

Notes

You don't have to, and you shouldn't run go install, as that will compile and install the packages in your GOPATH, which is often not wanted. Doing cross compilation is not for developing / testing your app and packages. It is to produce a single binary which you will run on another system / computer.

go build will not install anything, it will just produce the executable binary. For details, see What does go build build?

Also confirmed in blog post: Dave Cheney: Cross compilation with Go 1.5:

When cross compiling, you should use go build, not go install. This is the one of the few cases where go build is preferable to go install.

The reason for this is go install always caches compiled packages, .a files, into the pkg/directory that matches the root of the source code.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值