We are compiling our Go code to be run on docker and we were investigating why our binary was not executing. We found that it was missing some dynamic libraries (although we want statically linked binaries).
This is how it was compiled.
env GOOS=linux CGO_ENABLED=1 GO111MODULE=on GOPRIVATE=github.com/ourrepo GOPROXY=https://proxy.golang.org go build --installsuffix cgo --ldflags='-extldflags=-static' -o program main.go
Using the same build command with CGO_ENABLED=0
ended up fixing the issue, and the output binary was statically linked.
Now the weird part is we have another program that is using the same build command, this time with CGO_ENABLED=1
and... it is statically linked!
So I'm very confused why in some cases CGO_ENABLED=1
produces dynamic linking, and sometimes static linking. Happy to provide more details.
CGO_ENABLED=1
makes no difference. – TonemeCGO_ENABLED=0
is what you want, what are you trying to accomplish with the originalgo build
command? (that original command looks like a combination of random things just pasted together) – Toneme-static
to an external linker that you're not calling (there's no-linkmode external
), you don't seem to be cross-compiling, but you have GOOS defined, though no GOARCH; and you haveGO111MODULE=on
but you're not building a package. It looks like you added a bunch of options without knowing what they do, and it's causing confusion. – TonemeCGO_ENABLED=0
doesn't "magically" make it happen, it prevents the use of cgo, which will result in a static binary, which sounds like what you want. – Tonemeenv GOOS=linux GOARCH=amd64 GOPRIVATE=github.com/ourrepo GOPROXY=https://proxy.golang.org go build -o program main.go
and it is dynamically linked. Adding CGO_ENABLED=0 worked; I'm still not sure how things ended up statically linked in one case of CGO_ENABLED=1 – KilotonCGO_ENABLED=0
as we've already covered. – TonemeCGO_ENABLED=1
(which is usually the default) if you don't use cgo at all, because the default result of the go toolchain is a static binary. – Toneme