This is a creation in Article, where the information may have evolved or changed.
Before Go 1.5, cross-compiler is still a bit of a hassle, you need to massive scripts T to compile and host the machine different programs.
As described in the comes with supported for all architectures built in article, Go 1.5 is much simpler, you only need to set the GOOS and goarch Two environment variables can be born The go program to the desired platform.
For example, use the following code to test:
12345678 |
Package mainimport"FMT"import"Runtime"func Main () { Fmt. Printf ("OS:%s\narchitecture:%s\n", runtime.) GOOS, runtime. Goarch)} |
Compile it:$ GOOS=darwin GOARCH=386 go build test.go
You can build OS X
the program that runs on it.
The available OS and arch values are as follows:
|
$GOOS |
$GOARCH |
|
darwin |
386 |
|
darwin |
amd64 |
|
darwin |
arm |
|
darwin |
arm64 |
|
dragonfly |
amd64 |
|
freebsd |
386 |
|
freebsd |
amd64 |
|
freebsd |
arm |
|
linux |
386 |
|
linux |
amd64 |
|
linux |
arm |
|
linux |
arm64 |
|
linux |
ppc64 |
|
linux |
ppc64le |
|
netbsd |
386 |
|
netbsd |
amd64 |
|
netbsd |
arm |
|
openbsd |
386 |
|
openbsd |
amd64 |
|
openbsd |
arm |
|
plan9 |
386 |
|
plan9 |
amd64 |
|
solaris |
amd64 |
|
windows |
386 |
|
windows |
amd64 |
Libraries under different operating systems may have different implementations, such as the Syscall library. Go build does not have a built-in #define
or preprocessor-like processing platform-related code trade-offs, but the use of tag and file suffix implementation.
Tag mode
Tag follows the rules.
- A build tag is evaluated as the OR of space-separated options
- Each option evaluates as the and of its comma-separated terms
- Each of the alphanumeric word or, preceded by!, its negation
Add tag to the head of the file:
1 |
+build Darwin FreeBSD NetBSD OpenBSD |
can have multiple tags, which is the relationship between and
12 |
//+build Linux Darwin //+build 386 |
Note that there is a blank line separation between the tag and the package, and the following example is not true:
12 |
//+build!linux Package //Wrong |
File suffix method
Files with the _$goos.go suffix are compiled on this platform only, when the file does not exist on other platforms. The complete suffix is as follows:
such as Syscall_linux_amd64.go,syscall_windows_386.go,syscall_windows.go and so on.
Reference documents
- http://golangcookbook.com/chapters/running/cross-compiling/
- http://dave.cheney.net/2013/07/09/ An-introduction-to-cross-compilation-with-go-1-1
- http://dave.cheney.net/2015/03/03/ Cross-compilation-just-got-a-whole-lot-better-in-go-1-5
- https://golang.org/doc/install/source# Environment
- http://dave.cheney.net/2013/10/12/ How-to-use-conditional-compilation-with-the-go-build-tool