Golang 的跨平台編譯

Golang 可在任何平台上做 cross compile

所以可以在MacOSX編譯出Linux的可執行檔

只要給定編譯平台的環境變數

go build時就會依照環境變數

編譯出相對應的平台

env GOOS=target-OS GOARCH=target-architecture go build package-import-path

支援的 target os 跟 target architecture 如下表

`GOOS` - Target Operating System`GOARCH` - Target Platform
`android``arm`
`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`
`linux``mips`
`linux``mipsle`
`linux``mips64`
`linux``mips64le`
`netbsd``386`
`netbsd``amd64`
`netbsd``arm`
`openbsd``386`
`openbsd``amd64`
`openbsd``arm`
`plan9``386`
`plan9``amd64`
`solaris``amd64`
`windows``386`
`windows``amd64`

所以要在 Mac 上編譯出 Linux 的可執行檔

只需要如下指令:

GOOS=linux GOARCH=amd64 go build

這時候我們用 file 查看檔案屬性會發現是一個 LSB executable

ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, with debug_info, not stripped

留言

留言功能尚未啟用 — 設定 giscus(GitHub Discussions)後即會顯示。