Go 编译器默认编译出来的程序会带有符号表和调试信息,一般来说 release 版本可以去除调试信息以减小二进制体积。
-s:忽略符号表和调试信息。
-w:忽略DWARFv3调试信息,使用该选项后将无法使用gdb进行调试。
体积从 9.8M 下降到 7.8M,下降约 20%。
3 使用 upx 减小体积
3.1 upx 安装
UPX is an advanced executable file compressor. UPX will typically reduce the file size of programs and DLLs by around 50%-70%, thus reducing disk space, network load times, download times and other distribution and storage costs.
package main
import (
"log"
"net/http"
"net/rpc"
)
type Result struct {
Num, Ans int
}
type Calc int
// Square calculates the square of num
func (calc *Calc) Square(num int, result *Result) error {
result.Num = num
result.Ans = num * num
return nil
}
func main() {
rpc.Register(new(Calc))
rpc.HandleHTTP()
log.Printf("Serving RPC server on port %d", 1234)
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("Error serving: ", err)
}
}
$ go build -o server main.go
$ ls -lh server
-rwxr-xr-x 1 dj staff 9.8M Dec 7 23:57 server
$ go build -ldflags="-s -w" -o server main.go
$ ls -lh server
-rwxr-xr-x 1 dj staff 7.8M Dec 8 00:29 server
$ brew install upx
$ upx
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2020
UPX 3.96 Markus Oberhumer, Laszlo Molnar & John Reiser Jan 23rd 2020
Usage: upx [-123456789dlthVL] [-qvfk] [-o file] file..
...
Type 'upx --help' for more detailed help.
$ go build -o server main.go && upx -9 server
File size Ratio Format Name
-------------------- ------ ----------- -----------
10253684 -> 5210128 50.81% macho/amd64 server
$ ls -lh server
-rwxr-xr-x 1 dj staff 5.0M Dec 8 00:45 server
$ go build -ldflags="-s -w" -o server main.go && upx -9 server
File size Ratio Format Name
-------------------- ------ ----------- -----------
8213876 -> 3170320 38.60% macho/amd64 server
$ ls -lh server
-rwxr-xr-x 1 dj staff 3.0M Dec 8 00:47 server