Context:
go 1.2, ubuntu 12.10
Goal:
Reduce size of compiled binaries
Currently in my build process, I run "go install" to generate the binary. The I read from somewhere that if I pass in -w
it will shrink the binary. I tried it by passing it into the -ldflags
option & my binary lost 1MB in size.
-w
flag documented anywhere? What does it actually do?strip -s <binary>
command and ran that on top of -w
and got another weight loss of 750KB ! The resulting binary runs fine. Does stripping cause problems in any situations ?ldflags , then, stands for linker flags. It is called this because it passes a flag to the underlying Go toolchain linker, cmd/link , that allows you to change the values of imported packages at build time from the command line.
The go build tool allows us to pass options to the Linker, which is the component responsible for assembling the binary. We can pass options to the Linker by using the --ldflags flag to the build tool.
You will get the smallest binaries if you compile with -ldflags '-w -s'
.
The -w
turns off DWARF debugging information: you will not be able to use gdb
on the binary to look at specific functions or set breakpoints or get stack traces, because all the metadata gdb
needs will not be included. You will also not be able to use other tools that depend on the information, like pprof
profiling.
The -s
turns off generation of the Go symbol table: you will not be able to use go tool nm
to list the symbols in the binary. strip -s
is like passing -s
to -ldflags
but it doesn't strip quite as much. go tool nm
might still work after strip -s
. I am not completely sure.
None of these — not -ldflags -w
, not -ldflags -s
, not strip -s
— should affect the execution of the actual program. They only affect whether you can debug or analyze the program with other tools.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With