GoLang to build smaller executable file

Summary

Go executables often have a larger footprint than desired, but developers can employ specific strategies to significantly reduce their file size. A key approach involves using `go build` with the `-ldflags="-s -w"` parameters, which strip the symbol table, debug information, and DWARF data from the binary. These flags effectively shrink the executable without affecting its runtime functionality. For further optimization, the UPX tool can be applied to the compiled binary, achieving even greater compression. Combining these methods results in much smaller Go executable files, ideal for production environments.

Normally the executable file built with go is a bit large, it is always desired that a smaller executable file should be generated though. In this post, a couple of ways to reduce the size of the executable will be introduced. The end effect is that the executable file size would be much less than the normal generated one.

The file which is built normally has below size.

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       12/14/2019   9:47 AM        1974272 main-ori.exe

Add build flags

 Two ld parameters can be added when using go tool to build the project, they are -s and -w.

go build -ldflags="-s -w" main.go

-s: Omit the symbol table and debug information. They are not needed in a production environment in most of cases.

-w: Omit the DWARF information.

These two parameters don't affect the execution of the program but it will reduce the executable file size.

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       12/14/2019   9:48 AM        1427968 main-flag.exe

UPX compression

upx a tool for binary compression. It can be used to compress binary file and can reduce file size further.

The command to compress the file is:

upx main.exe

After compression, the file size becomes much smaller.

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       12/14/2019   9:52 AM         495616 main.exe

Happy coding.

GOLANG EXECUTABLE

  RELATED

  COMMENTS

2
Anonymous
Dec 13, 2019 at 9:12 pm

Not recommended to use UPX, you going to waste more memory by loading uncompressed Go binary, other have discuss but you don't have to copied the same contents from others.

Beside, your Javascript alert message is not user friendly.

Anonymous
Dec 13, 2019 at 9:39 pm

This is knowledge which everyone can gets, it doesn't necessarrily mean others cannot write similar stuff even though someone writes it.

Your initial point is discussable but it's confusing.