People familiar with Golang know that Golang cross-compiling is very simple, just set up a few environment variables can be
# mac上编译linux和windows二进制CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build # linux上编译mac和windows二进制CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build# windows上编译mac和linux二进制SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build main.goSET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build main.go
What are the values of GOOS and goarch, can be searched online, a lot of
But cross-compilation is not support CGO, that is, if you have C code in the code, is not compiled, for example, your program used the SQLite database, in the compilation of Go-sqlite driver, according to the above procedure is compiled do not pass
Need CGO support, to change the cgo_enabled 0 to 1, that is CGO_ENABLED=1
, also need to set the compiler, for example, I want to compile the arm version of the binary on Linux, need to do this:
This arm-linux-gnueabi-gcc
is a what thing, how to install, if your system is Ubuntu, you can follow the following command to install:
sudo apt-get install g++-arm-linux-gnueabisudo apt-get install gcc-arm-linux-gnueabi
Successful installation can be compiled, but if you want to compile the Mac version, or want to build Linux on the Mac version, window version, one installation is too slow, the system command can be installed fortunately, the system command is not supported, then you have to search, and then find the address, download, installation, time-consuming and laborious
This tool is available on GitHub Https://github.com/karalabe/xgo
It is a Docker image, which integrates a variety of platform compiler, according to its tutorial, it is easy to compile the binary files of each platform, the installation time is more time-consuming, need to download about 1 g of data, but the effect is the leverage
The default is to compile the binaries for all platforms, which can be time-consuming, and if you only need a binary for a particular platform, use the -targets
parameters
Image.png
Notice it's -targets
not --targets
, I'm going to fail when I test myself. --targets