108

In C, we can build a debug version or a release version of the binary files (the object files and the executable). How can we do this in Go?

0

4 Answers 4

169

In Go, it isn't typical to have a debug version or a release version.

By default, go build combines symbol and debug info with binary files. However, you can remove the symbol and debug info with go build -ldflags "-s -w".

Sign up to request clarification or add additional context in comments.

9 Comments

There's some documentation on this here - golang.org/doc/gdb#Introduction.
You're right, but I think there's a good reason it's not typical to strip symbols--if you get a report of a panic out in the wild, for example, it'd be great to have the symbols there for an informative stacktrace.
I think "-s" (omit symbol table and debug info) already includes "-w" (omit DWARF symbol table), so there should be no need to specify both. With the executable I tried this on, "-s -w" gives exactly the same size as "-s" alone.
It would appear that -s doesn't affect GOOS=darwin
Just made some experiments on my Mac. Results: -s does not imply -w, binary size with/without -s is the same. -w reduces binary from 12 to 8MB. ALSO: there's NO difference in stack-traces between "go build" and "-s -w" builds. Of course it's just for my software, probably there are corner cases.
|
30

You can instruct the linker to strip debug symbols by using

go install -ldflags '-s'

I just tried it on a fairly large executable (one of the GXUI samples), and this reduced it from ~16M to ~10M. As always, your mileage may vary...

Here is a full list of all linker options.

Comments

1

The accepted and high-rated answer doesn't work for me. While binary files generated by go build do include debug symbols, they are compiled with optimization enabled, which makes it almost impossible to debug with delve.

The following option works for me (I find it in delve document):

go build -gcflags="all=-N -l"

Comments

0

As stated earlier, there is no such thing as a "debug" or "release" binaries in Go.

However, there is a specific build environment variable called CGO_ENABLED. Which is enabled by default. And will most likely make your binary larger.

However when you deploy your binary for a scratch Docker image consider setting CGO_ENABLED=0 - as no host OS needs to be bundled.

Unless you use packages that contains C code, which in that case CGO_ENABLED need to be set to 1.

Also there is a GOOS environment variable, which you might want to set explicitly to for example linux.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.