Elwinar

Minimalist by design

Statically link Golang binaries

2015.12.26

The standard way to really statically compile a Golang binary is to disable cgo by setting the environment variable CGO_ENABLED to false.

CGO_ENABLED=0 go build

Which obviously doesn’t work when you need cgo, like for the sqlite driver.

The solution isn’t a new feature, I found it in a github repository luckily named go-sqlite-static that doesn’t contain much except that.

go build -ldflags '-linkmode external -extldflags -static -w'

The trick here is to tell gc ((the Golang compiler) to use an external linker instead of its own to do the final step of the compilation. In my case, gcc’s linker is used, hence the -static flag to produce a statically linked executable.

Et voilĂ  !