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
.
= ["386","amd64"]
arch_targets = ["darwin", "linux", "windows"]
os_targets
= 'main'
program_name = './main.go'
file_to_compile
.each do |os|
os_targets.each do |arch|
arch_targets
= program_name + '_' + os + '_' + arch
file_name ENV['GOOS'] = os
ENV['GOARCH'] = arch
= 'go build -o build/' + file_name + " " + file_to_compile
command
system(command)
if os == 'windows'
File.rename('./build/'+file_name, './build/'+file_name+'.exe')
end
end
end
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.
Have any feedback?
Please feel free to send me a mail! I would love to hear from you.