This tutorial aims to guide you through the steps involved in cross-compiling Go applications for different operating systems. By the end of this tutorial, you will be able to build Go applications that can run on various platforms from one single codebase.
Cross-compiling in Go is made possible by the GOOS and GOARCH environment variables. These variables allow you to specify the target operating system (OS) and architecture respectively.
Let's say we have a simple Go program that we want to compile for different OS. The code is as follows:
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Printf("OS: %s, Arch: %s\n", runtime.GOOS, runtime.GOARCH)
}
This program prints the OS and architecture it was built for when it is run.
To build this for a Windows 64-bit system, we would set the GOOS to "windows" and the GOARCH to "amd64". The command would look like this:
GOOS=windows GOARCH=amd64 go build main.go
This will output a file named main.exe
, which can be run on a Windows 64-bit system.
To compile the same program for a Linux 32-bit system, we would set the GOOS to "linux" and the GOARCH to "386". The command would look like this:
GOOS=linux GOARCH=386 go build main.go
This will output a file named main
, which can be run on a Linux 32-bit system.
For a MacOS 64-bit system, we would set the GOOS to "darwin" and the GOARCH to "amd64". The command would look like this:
GOOS=darwin GOARCH=amd64 go build main.go
This will output a file named main
, which can be run on a MacOS 64-bit system.
In this tutorial, we have learned about cross-compiling Go applications for different operating systems. We learned how to use the GOOS and GOARCH environment variables to specify the target OS and architecture.
For further learning, you can explore more about the different values available for GOOS and GOARCH, and experiment with cross-compiling your Go programs for those different platforms.
You can also look into how to automate this process using build scripts or continuous integration tools.
Here are some exercises for you to practice:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
Compile for Windows 32-bit: GOOS=windows GOARCH=386 go build main.go
package main
import (
"fmt"
"os"
"strconv"
)
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
func main() {
arg := os.Args[1]
n, _ := strconv.Atoi(arg)
fmt.Printf("Factorial of %d is %d\n", n, factorial(n))
}
Compile for Linux ARM: GOOS=linux GOARCH=arm go build main.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println("You entered:", text)
}
Compile for MacOS 64-bit: GOOS=darwin GOARCH=amd64 go build main.go
With these exercises, you'll get hands-on experience with cross-compiling Go applications for different operating systems.