Compiling Your Tool for Different Platforms

Powerful Command-Line Applications in Go — by Ricardo Gerardi (14 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding Command-Line Flags | TOC | Exercises 👉

By default, the go build tool builds an executable binary for the current operating system and architecture. You can also use go build to build your command-line tool for a different platform even if you don’t have access to that platform. For example, if you’re using Linux, you can build a Windows or macOS binary that can be executed on those platforms without Go installed. This process is called cross-compilation. Let’s build the word counter tool for the Windows platform by setting the GOOS environment variable to windows before running the build tool:

​ ​$ ​​GOOS=windows​​ ​​go​​ ​​build​
​ ​$ ​​ls​
​ go.mod main.go main_test.go wc wc.exe

Use the file command to get information about the new wc.exe file:

​ ​$ ​​file​​ ​​wc.exe​
​ wc.exe: PE32+ executable (console) x86-64 (stripped to external PDB),
​ for MS Windows

As you can see, this creates a 64-bit executable file wc.exe for the Windows platform.

The documentation for go build contains a list[11] with all of the supported values for the GOOS environment variable.

Since this is a static binary, it doesn’t require any runtime dependencies or anything else to run. Transfer this file directly to a Windows machine using your…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.