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.

猜你喜欢

转载自blog.csdn.net/lulitianyu/article/details/85272200