29

To compile a Go program you type go build myprogram.go, can you pass an optimization flags along or the code is always compiled in the same way? I am talking about speed optimizations, code size optimizations or other optimizations.

I know if you use gccgo you just pass -O2 or -O0 but my question is about an official Go compiler go.

phuclv
  • 37,963
  • 15
  • 156
  • 475
exebook
  • 32,014
  • 33
  • 141
  • 226
  • 3
    https://golang.org/cmd/compile/ has an option to *disable* optimizations. – muru Jul 10 '17 at 03:28
  • Does this answer your question? [How to build a release version binary in Go?](https://stackoverflow.com/questions/29599209/how-to-build-a-release-version-binary-in-go) – phuclv Apr 19 '22 at 06:15
  • 1
    @phuclv: The linked duplicate is missing answers that point out the possibility of disabling optimization and inlining. It's fine to point out that it's normal not to do that, but if optimized vs. non-optimized is not even useful at all for a Go debug build, then these questions aren't duplicates. (Useful for them to link to each other, though.) – Peter Cordes Apr 19 '22 at 06:40

2 Answers2

27

Actually no explicit flags, this Go wiki page lists optimizations done by the Go compiler and there was a discussion around this topic in golang-nuts groups.

You can turn off optimization and inlining in Go gc compilers for debugging.

-gcflags '-N -l'
  • -N : Disable optimizations
  • -l : Disable inlining
Azeem
  • 11,148
  • 4
  • 27
  • 40
jeevatkm
  • 4,571
  • 1
  • 23
  • 24
11

If you're looking to optimize the binary size, you can omit the symbol table, debug information and the DWARF symbol table by passing -s and -w to the Go linker:

$ go build -o mybinary -ldflags="-s -w" src.go

(source blog post which includes some benchmarks)

fstanis
  • 5,234
  • 1
  • 23
  • 42