Golang静态编译+体积优化

用Golang写了个E5续费小工具,用了gin+gorm(sqlite3),静态编译后能运行,但是体积较大,使用如下方法进行优化,做个小记录

  1. 静态编译去除无用信息

    go build -a -ldflags '-s -w -extldflags "-static"' .
  2. 使用upx壳压缩

    upx xxx

优化前体积 21M:

优化前体积

优化后体积 5.7M:

优化后体积

后面又打包windows执行文件,发现打包完后在windows下启动报错:

failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub

image-20220601214922212

之前在Linux上打包也有遇到这个问题,知道是sqlite3静态编译的问题,解决办法:

在Linux中安装mingw-windows版本用以交叉编译,以下命令:

apt-get install gcc-mingw-w64
apt-get install gcc-multilib

然后使用下面的命令打包:

env CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc CXX=x86_64-w64-mingw32-g++ GOOS=windows GOARCH=amd64 go build -a -ldflags '-s -w -extldflags "-static"' .

之后便可以成功在Windows下运行了

最后修改:2022 年 06 月 01 日
如果觉得我的文章对你有用,请随意赞赏