How to cross compile Go with CGO programs for a different OS/Arch

How to cross compile Go with CGO programs for a different OS/Arch

It is possible to compile Go programs for a different OS, even though go build says otherwise.

You’ll need:

First of all, clone the Go repo and switch to tip:

  1. $ hg clone -u release
  2. $ cd go
  3. go$ hg update default

Apply the patch:

  1. go$ curl | patch -p1
  2. patching file src/cmd/go/build.go

Build Go:

  1. go$ cd src
  2. go/src$ bash all.bash

Now use golang-crosscompiler to build all the toolchains

  1. go$ git clone
  2. go$ source golang-crosscompile/crosscompile.bash
  3. go$ go-crosscompile-build-all
  4. go-crosscompile-build darwin/386
  5. # Building C bootstrap tool.
  6. ....
  7. ---
  8. Installed Go for windows/amd64 in /usr/local/go
  9. 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:

  1. $ 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:

  1. $ 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):

  1. $ CC=arm-linux-gnueabihf-gcc GOOS=linux GOARCH=arm GOARM=6 CGO_ENABLED=1 go build -v -o myprogram -ldflags="-extld=$CC"
ft_authoradmin  ft_create_time2019-11-18 12:24
 ft_update_time2019-11-18 12:25