Go Wiki:使用 Linux 建置 Windows Go 程式

此處檢視可用的 GOOSGOARCH 值。

Go 版本 >= 1.5

自 Go 1.5 版本以來,純粹 Go 可執行檔的交叉編譯變得非常容易。使用下列程式碼試試看。您可以在Dave Cheney的部落格文章中找到更多資訊。

$ cat hello.go
package main

import "fmt"

func main() {
        fmt.Printf("Hello\n")
}
$ GOOS=windows GOARCH=386 go build -o hello.exe hello.go

在 cmd.exe 中,而非 PowerShell

$ set GOOS=windows
$ set GOARCH=386
$ go build -o hello.exe hello.go

您現在可以在鄰近的 Windows 電腦上執行 hello.exe

請注意,您第一次執行上述指令時,它會在背景重新建置大部分的標準函式庫,因此會相當耗時。後續的建置會較快,因為 Go 指令建置快取。

另請注意,當 cross-compiling 時,cgo 已停用,因此任何提到 import "C" 的檔案將會被 program 忽略(請參閱 https://github.com/golang/go/issues/24068)。若要使用 cgo,或任何其他建立模式,例如 c-archivec-sharedsharedplugin,則您必須擁有一個 C cross-compiler。

較舊的 Go 版本 (<1.5)

我使用的是 linux/386,不過我猜測此程序也適用於其他主機平台。

準備 (若有需要)

sudo apt-get install gcc
export go env GOROOT

第一步是建立主機版本的 Go

cd $GOROOT/src
sudo -E GOOS=windows GOARCH=386 PATH=$PATH ./make.bash

接著你需要建立其他 Go 編譯器和連結器。我有個小程式可以做到這點

$ cat ~/bin/buildcmd
#!/bin/sh
set -e
for arch in 8 6; do
    for cmd in a c g l; do
        go tool dist install -v cmd/$arch$cmd
    done
done
exit 0

最後一步是建立 Windows 版本的標準指令和函式庫。我也有個小型腳本可以做到這點

$ cat ~/bin/buildpkg
#!/bin/sh
if [ -z "$1" ]; then
    echo 'GOOS is not specified' 1>&2
    exit 2
else
    export GOOS=$1
    if [ "$GOOS" = "windows" ]; then
        export CGO_ENABLED=0
    fi
fi
shift
if [ -n "$1" ]; then
    export GOARCH=$1
fi
cd $GOROOT/src
go tool dist install -v pkg/runtime
go install -v -a std

我是這麼執行的

$ ~/bin/buildpkg windows 386

以建立 Windows/386版本的 Go 指令和封包。您可能會從我的腳本中看出,我排除建立任何與 cgo 有關的部分 – 這些部分對我來說沒用,因為我沒有安裝對應的 gcc cross-compiling 工具。所以我只跳過那些。

現在我們已經準備好建立我們的 Windows 可執行檔

$ cat hello.go
package main

import "fmt"

func main() {
        fmt.Printf("Hello\n")
}
$ GOOS=windows GOARCH=386 go build -o hello.exe hello.go

我們只需要找一台 Windows 電腦來執行我們的 hello.exe


此內容是 Go Wiki 的一部分。