优化 go build 可执行文件过大的问题
原始大小
(以 macOS 为例)
按照一般方式 build,在本例子中,可以看到生成文件为 10M。
GOOS=darwin GOARCH=amd64 CGO_ENABLED=1 go build
![](https://rmb.ee/wp-content/uploads/2022/10/033f4bd1-2d68-7f61-c98b-bc8e0f7a97ef.png)
优化
第一步
省略调试信息及符号表。
GOOS=darwin GOARCH=amd64 CGO_ENABLED=1 go build -ldflags="-w -s"
-w Omit the DWARF symbol table.
-s Omit the symbol table and debug information.
可以看到体积减小到7.3M (比起始大小-27%)。
![](https://rmb.ee/wp-content/uploads/2022/10/5b298871-ce35-bd1a-bdbf-c8c0125ec474.png)
第二步
安装 upx,对文件进一步压缩。
brew install upx
upx appname
可以看到体积骤减至2.9M。(2次优化后比起始大小-71%)
![](https://rmb.ee/wp-content/uploads/2022/10/93a9f206-bf3c-85f4-bcc8-056e17ff2b0e.png)