由于Go语言是静态编译的,编译打包之后基本就不会再对其他类库有依赖,所以Go语言的可执行文件会比较大。例如,《Windows环境下将Go语言编译为DLL并供.Net调用》中的例子所输出的DLL文件就高达16MB(当然,这个例子中还有其他的代码):
一、删除符号表和调试信息
首先,我们通过编译参数-ldflags删除符号表和调试信息:
1 |
go build -ldflags "-s -w" -buildmode=c-shared -o exportgo.dll main.go |
可以发现大小了5MB:
如果要深究参数的含义,可以查看go build的帮助:
1 2 |
C:\>go help build usage: go build [-o output] [-i] [build flags] [packages] |
其中 -ldflags是传递给 go tool link的参数:
1 2 |
-ldflags '[pattern=]arg list' arguments to pass on each go tool link invocation. |
而:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
C:\>go tool link usage: link [options] main.o -B note add an ELF NT_GNU_BUILD_ID note when using ELF -D address set data segment address (default -1) -E entry set entry symbol name -H type set header type -I linker use linker as ELF dynamic linker -L directory add specified directory to library path -R quantum set address rounding quantum (default -1) -T address set text segment address (default -1) -V print version and exit -X definition add string value definition of the form importpath.name=value -a disassemble output -buildid id record id as Go toolchain build id -buildmode mode set build mode -c dump call graph -cpuprofile file write cpu profile to file -d disable dynamic executable -debugtramp int debug trampolines -dumpdep dump symbol dependency graph -extar string archive program for buildmode=c-archive -extld linker use linker when linking in external mode -extldflags flags pass flags to external linker -f ignore version mismatch -g disable go package data checks -h halt on error -importcfg file read import configuration from file -installsuffix suffix set package directory suffix -k symbol set field tracking symbol -libgcc string compiler support lib for internal linking; use "none" to disable -linkmode mode set link mode -linkshared link against installed Go shared libraries -memprofile file write memory profile to file -memprofilerate rate set runtime.MemProfileRate to rate -msan enable MSan interface -n dump symbol table -o file write output to file -pluginpath string full path name for plugin -r path set the ELF dynamic linker search path to dir1:dir2:... -race enable race detector -s disable symbol table -tmpdir directory use directory for temporary files -u reject unsafe packages -v print link trace -w disable DWARF generation |
其中的-s删除了符号表、-w删除了调试信息。
二、UPX压缩
其次,我们使用UPX(https://upx.github.io)进行压缩:
可执行文件从11MB压缩到了3.8MB。
最终实现的压缩效果为3.8/16=24%,即压缩后的大小是压缩前的四分之一。
转载时请保留出处,违法转载追究到底:进城务工人员小梅 » Go语言生成的可执行文件瘦身