How To Shrink a Go Executable

In this post, I’ll show you how to shrink your Go executable file (the output of go build). Go binaries can be quite large. For example, the simple ‘Hello world’ from the Go Tutorial introduction turns into a 2.8MB binary on Windows. If you don’t care about the size of your executables, that’s fine. With modern hard disks and network speeds, it doesn’t matter too much.

If you do care, read on! There are some tricks to reduce the output size considerably. This post shows two quick and easy ways to shrink your go executable.

Why would you need to shrink your Go executable?

Go binaries are quite large compared to equivalent C programs. This is because Go needs to include stuff like the garbage collector that we can’t get around. However, it also includes some unnecessary things you can strip.

If you are creating software to share with the world, it’s important to consider your file size. After all, your software might be downloaded thousands or even millions of times. Each byte you can strip off is a byte that does not have to be stored on millions of hard disks or transferred over the Internet.

Luckily, you can considerably reduce a Go binary with little effort.

Strip debug symbols

First of all, you can strip some stuff from your binary file that is only needed for debugging. Since it’s quite rare to debug a release version (and you can also build it again if you ever need to), you can safely remove debug symbols and such from the binary by using some ldflags: -ldflags="-s -w"

To learn what these flags do, you can check the output of the command go tool link. But I did that for you already, so here you go:

  • -s disables the symbol table
  • -w disables DWARF generation

Your go build command should look like this when using these flags:

go build -ldflags="-s -w"

Please note that you need to be using modules for this to work. E.g., the above command won’t work if you are compiling a single file.

Compress your executable

This is not Go-specific; it works for any executable. There are multiple tools out there to compress executables. One such tool, upx, is open-source and freely available. You can also use it on many different OSes, and it will usually compress your file considerably.