Automating Cross Compiling Go Programs on Linux

Programs written in Go can be compiled for a variety of different targets. Cross compiling is easy, but takes a lot of effort.

In order to automate cross compilation the following Ruby script is built to take that burden off you.

Save the script in a file (for example with the name compile.rb) in the directory where you would like to compile and run it using ruby compile.rb.

arch_targets = ["386","amd64"]
os_targets = ["darwin", "linux", "windows"]

program_name = 'main'
file_to_compile = './main.go'

os_targets.each do |os|
    arch_targets.each do |arch|

        file_name = program_name + '_' + os + '_' + arch
        ENV['GOOS'] = os
        ENV['GOARCH'] = arch

        command = 'go build -o build/' + file_name + " " + file_to_compile


        if os == 'windows'
            File.rename('./build/'+file_name, './build/'+file_name+'.exe')

About the script:

  • In the array arch_targets we specify which computer architectures we want to compile for. Some supported architectures are: arm, 386, arm64, amd64
  • In the array os_targets we specify which operating system we want to compile for. Some supported operating systems are: android, darwin, freebsd, linux, openbsd, netbsd, windows.
  • program_name is the name of the executable after compilation.
  • file_to_compile is the name of the file you would like to compile, or your entry file containing your main function in case your program contains multiple files.


Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
© 2020