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
endAbout the script:
- In the array
arch_targetswe specify which computer architectures we want to compile for. Some supported architectures are:arm,386,arm64,amd64 - In the array
os_targetswe specify which operating system we want to compile for. Some supported operating systems are:android,darwin,freebsd,linux,openbsd,netbsd,windows. program_nameis the name of the executable after compilation.file_to_compileis 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.
Have any feedback?
Please feel free to send me a mail! I would love to hear from you.