Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for huge size of compiled executable of Go

Tags:

go

executable

I complied a hello world Go program which generated native executable on my linux machine. But I was surprised to see the size of the simple Hello world Go program, it was 1.9MB !

Why is it that the executable of such a simple program in Go is so huge?

like image 431
Karthic Rao Avatar asked Feb 18 '15 04:02

Karthic Rao


People also ask

What determines the size of an executable?

Apparently the most significant factor is the number of bytes the compiler writes out to the resulting file. Basically what you're asking is: "What does my binary executable actually contain?"

Can go be compiled to EXE?

From the command line in the hello directory, run the go build command to compile the code into an executable. From the command line in the hello directory, run the new hello executable to confirm that the code works.

Is compiled code smaller?

typically, compiled code is smaller than the source code it is compiled from.


1 Answers

This exact question appears in the official FAQ: Why is my trivial program such a large binary?

Quoting the answer:

The linkers in the gc tool chain (5l, 6l, and 8l) do static linking. All Go binaries therefore include the Go run-time, along with the run-time type information necessary to support dynamic type checks, reflection, and even panic-time stack traces.

A simple C "hello, world" program compiled and linked statically using gcc on Linux is around 750 kB, including an implementation of printf. An equivalent Go program using fmt.Printf is around 1.9 MB, but that includes more powerful run-time support and type information.

So the native executable of your Hello World is 1.9 MB because it contains a runtime which provides garbage collection, reflection and many other features (which your program might not really use, but it's there). And the implementation of the fmt package which you used to print the "Hello World" text (plus its dependencies).

Now try the following: add another fmt.Println("Hello World! Again") line to your program and compile it again. The result will not be 2x 1.9MB, but still just 1.9 MB! Yes, because all the used libraries (fmt and its dependencies) and the runtime are already added to the executable (and so just a few more bytes will be added to print the 2nd text which you just added).

like image 188
icza Avatar answered Oct 12 '22 09:10

icza