It is possible to compile Go programs for a different OS, even though go build
says otherwise.
You'll need:
- a valid toolchain for the platform/os you're targetting
- Go Tip (works on 1.1 and 1.2rc1 but you might as well be on tip)
golang-crosscompile
helper script https://github.com/davecheney/golang-crosscompile- the patch provided
First of all, clone the Go repo and switch to tip:
$ hg clone -u release https://code.google.com/p/go
$ cd go
go$ hg update default
Apply the patch:
go$ curl https://gist.github.com/steeve/6905542/raw/cross_compile_goos.patch | patch -p1
patching file src/cmd/go/build.go
Build Go:
go$ cd src
go/src$ bash all.bash
Now use golang-crosscompiler
to build all the toolchains
go$ git clone https://github.com/davecheney/golang-crosscompile.git
go$ source golang-crosscompile/crosscompile.bash
go$ go-crosscompile-build-all
go-crosscompile-build darwin/386
# Building C bootstrap tool.
....
---
Installed Go for windows/amd64 in /usr/local/go
Installed commands in /usr/local/go/bin
Almost there, now a little cmd-fu and you're done. Just set the CC
env var to your toolchain's gcc
, set the proper GOOS
, GOARCH
, GOARM
(if needed) and finally the proper -extld
ldflag
.
Cross compiling from darwin/amd64
to windows/386
:
$ CC=i586-mingw32-gcc GOOS=windows GOARCH=386 CGO_ENABLED=1 go build -v -o myprogram.exe -ldflags="-extld=$CC"
Cross compiling from darwin/amd64
to linux/amd64
:
$ CC=x86_64-pc-linux-gcc GOOS=linux GOARCH=amd64 CGO_ENABLED=1 go build -v -o myprogram -ldflags="-extld=$CC"
Cross compiling from linux/amd64
to linux/arm
(in that case a Raspberry Pi):
$ CC=arm-linux-gnueabihf-gcc GOOS=linux GOARCH=arm GOARM=6 CGO_ENABLED=1 go build -v -o myprogram -ldflags="-extld=$CC"
For the CGO_Enabled issues i as able to fix mine this way
Install MinGW-w64: If you haven't already, install the MinGW-w64 toolchain. On Ubuntu, you can do this with the following command:
sudo apt-get install mingw-w64
Set the CC Environment Variable: Before running the go build command, set the CC environment variable to point to the MinGW-w64 C compiler. For example:
export CC=/usr/bin/x86_64-w64-mingw32-gcc
Build Your Application: Now try building your Go application again with the same GOOS, GOARCH, and CGO_ENABLED environment variables:
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 go build -o BPSMailer.exe
If you continue to experience issues, it may be helpful to check the documentation for the MinGW-w64 toolchain or seek assistance from the Go community, as they may have encountered similar issues when cross-compiling Go applications for Windows.
![image]()