Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the w flag mean when passed in via the ldflags option to the go command?

Tags:

go

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.

  1. Is this -w flag documented anywhere? What does it actually do?
  2. I then discovered the 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 ?
like image 975
canadadry Avatar asked Mar 08 '14 08:03

canadadry


People also ask

What does Ldflags mean?

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.

What is go build ldflags?

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.


1 Answers

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.

like image 81
Russ Cox Avatar answered Sep 17 '22 13:09

Russ Cox