Sunday, May 21, 2017

Automated Cross Compilation in Go

Cross compilation has been touched on before for Go, but one thing about it was always a little frustrating to me, and that was that the manual redefining of environment variables for multiple compilations took a long time and required manual tuning.

There are two observations we can make that can change this, and can automate multiple compilations in way that's universal across platforms:

  1. You can call Go from within Go
  2.  exec.Command("go", "build", "-o", output, packageName).Run()  
    
  3. You can define environment variables from within Go
  4.  os.Setenv("GOOS", "windows")
     os.Setenv("GOARCH", "386")  
With this in mind, we can built a script in Go that automates cross compilation! For each OS/Arch pair we want to compile, we can set the environment variables and run go build with a unique output name. Because Go provides a list of all valid OS/Arch pairs, we can also write a script that accepts variable packages and pair definitions, and you can find that script here.

This doesn't change how long it takes, as compiling for 20 different platforms involves recompiling a lot of the Go standard library every time, but it does mean we don't need to sit around and wait for each compilation to end to write in the next pair to compile for, and because the script itself is written in Go, we know the script will work on all Go platforms, whereas bash would have issues with windows. 

No comments:

Post a Comment