This is a creation in Article, where the information may have evolved or changed.
Objective
Recently, after writing a CLI program, the habitual go build found that the simple lines of code packaged out to 3.0+MB, for this was made Python classmate laughed for a long time, so they studied the go build resulting executable file compression
code example
The code is as follows:
package mainimport ( "os" "gopkg.in/urfave/cli.v2")const ( APP_NAME = "etcd-cli" APP_VERSION = "0.1" APP_USAGE = "etcd-cli是一个简单实用的etcd命令行客户端,帮助你彻底解脱一次又一次的输入etcdctl")func main() { app := new(cli.App) app.Name = APP_NAME app.Version = APP_VERSION app.Usage = APP_USAGE app.Action = action app.Run(os.Args)}func action(ctx *cli.Context) error { return nil}
General packaging methods and results
$ go build$ ls -lh-rwxr-xr-x 1 gangan staff 3.4M Aug 18 00:38 etcd-cli-rw-r--r-- 1 gangan staff 456B Aug 18 00:34 main.go
Can see, just more than 10 lines of code nothing has been implemented, and then go build got a 3.4MB executable file, it is conceivable that the product development go build will not be small, then there is no solution? There, see below.
Compress executable Files
First add the compilation parameters-ldflags
$ go build -ldflags '-w -s'$ ls -lh-rwxr-xr-x 1 gangan staff 2.5M Aug 18 00:45 etcd-cli-rw-r--r-- 1 gangan staff 456B Aug 18 00:34 main.go
Can be found in the small nearly 1MB
Practical UPX compression, Mac and win all have, here take Mac for example
$ brew install upx$ upx etcd-cli# 此处省略压缩时的打印...$ ls -lh-rwxr-xr-x 1 gangan staff 897K Aug 18 00:49 etcd-cli-rw-r--r-- 1 gangan staff 456B Aug 18 00:34 main.go
OK, the executable file from 3.4MB compression to 897K, the effect is very obvious, there is a need to quickly try it.
Written in the last
Golang Development program will be relatively large, this is because the Golang is statically compiled, after the compilation is basically no longer dependent on the other class libraries, so it will be relatively large. For example: C + + program can call DLL, so when packaging can not put the DLL into the package naturally small. I have seen some people use GO -> C -- dll --> C -> GO the way to indirectly implement the pseudo-dynamic link Golang, interested students can study.