Automating Cross Compiling Go Programs on Linux

2 Jul 2018 • Programming

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

        system(command)

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

About the script:



Have any feedback?

Please feel free to send me a mail! I would love to hear from you.