Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce compiled file size?

Tags:

go

Lets compare c and go: Hello_world.c :

#include<stdio.h> int main(){     printf("Hello world!"); } 

Hello_world.go:

package main import "fmt" func main(){     fmt.Printf("Hello world!") } 

Compile both:

$gcc Hello_world.c -o Hello_c  $8g Hello_world.go -o Hello_go.8 $8l Hello_go.8 -o Hello_go 

and ... what is it?

$ls -ls ... 5,4K 2010-10-05 11:09 Hello_c ... 991K 2010-10-05 11:17 Hello_go 

About 1Mb Hello world. Are you kidding me? What I do wrong?

(strip Hello_go -> 893K only)

like image 435
zyrg Avatar asked Oct 05 '10 07:10

zyrg


People also ask

How do I make the binaries smaller?

At first, use two go build flags, and create your executable like this: go build -ldflags="-s -w" . And then use UPX to make your executable smaller.

Is compiled code smaller?

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

Why is binary so large?

in Go 1.2, a decision was made to pre-expand the line table in the executable file into its final format suitable for direct use at run-time, without an additional decompression step. In other words, the Go team decided to make executable files larger to save up on initialization time.


2 Answers

If you are using a Unix-based system (e.g. Linux or Mac OSX) you could try removing the debugging information included in the executable by building it with the -w flag:

go build -ldflags "-w" prog.go 

The file sizes are reduced dramatically.

For more details visit the GDB's page: http://golang.org/doc/gdb

like image 104
Amged Rustom Avatar answered Oct 22 '22 05:10

Amged Rustom


The 2016 answer:

1. Use Go 1.7

2. Compile with go build -ldflags "-s -w"

➜ ls -lh hello -rwxr-xr-x 1 oneofone oneofone 976K May 26 20:49 hello* 

3. Then use upx, goupx is no longer needed since 1.6.

➜ ls -lh hello -rwxr-xr-x 1 oneofone oneofone 367K May 26 20:49 hello* 
like image 28
OneOfOne Avatar answered Oct 22 '22 05:10

OneOfOne