DEV Community

Cover image for Go Course: Build
Karan Pratap Singh
Karan Pratap Singh

Posted on • Originally published at karanpratapsingh.com

Go Course: Build

Building static binaries is one of the best features of Go which enables us to ship our code efficiently.

We can do this very easily using the go build command.

package main

import "fmt"

func main() {
    fmt.Println("I am a binary!")
}
Enter fullscreen mode Exit fullscreen mode
$ go build
Enter fullscreen mode Exit fullscreen mode

This should produce a binary with the name of our module. For example, here we have example.

We can also specify the output.

$ go build -o app
Enter fullscreen mode Exit fullscreen mode

Now to run this, we simply need to execute it.

$ ./app
I am a binary!
Enter fullscreen mode Exit fullscreen mode

Yes, it's as simple as that!

Now, let's talk about some important build time variables, starting with:

  • GOOS and GOARCH

these environment variables help use build go programs for different operating systems
and underlying processor architectures.

We can list all the supported architecture using go tool command.

$ go tool dist list
android/amd64
ios/amd64
js/wasm
linux/amd64
windows/arm64
.
.
.
Enter fullscreen mode Exit fullscreen mode

Here's an example for building a window's executable from macOS!

$ GOOS=windows GOARCH=amd64 go build -o app.exe
Enter fullscreen mode Exit fullscreen mode
  • CGO_ENABLED

This variable allows us to configure CGO, which is a way in Go to call C code.

This helps us to produce a statically linked binary that works without any external dependencies.

This is quite helpful for, let's say when we want to run our go binaries in a docker container with minimum external dependencies.

Here's an example of how to use it:

$ CGO_ENABLED=0 go build -o app
Enter fullscreen mode Exit fullscreen mode

This article is part of my open source Go Course available on Github.

GitHub logo karanpratapsingh / learn-go

Master the fundamentals and advanced features of the Go programming language

Learn Go

Hey, welcome to the course, and thanks for learning Go. I hope this course provides a great learning experience.

This course is also available on my website and as an ebook on leanpub. Please leave a ⭐ as motivation if this was helpful!

Table of contents

What is Go?

Go (also known as Golang) is a programming language developed at Google in 2007 and open-sourced in 2009.

It focuses on simplicity, reliability, and efficiency. It was designed to combine the efficacy, speed…

Top comments (0)