Home >Backend Development >Golang >Why are both `CGO_ENABLED=0` and `-ldflags \'-extldflags \'-static\'\'` necessary for creating static Go binaries?
How to Create Static Binaries in Go
When building Docker images based on scratch, users may encounter an error when executing binaries due to missing libraries. This can be resolved by setting both CGO_ENABLED=0 and -ldflags '-extldflags "-static"' flags during compilation.
Why Are Both Flags Necessary?
CGO_ENABLED=0 disables the use of C code in Go, ensuring that the binary does not depend on external C libraries.
-ldflags '-extldflags "-static"' instructs the linker to build a statically linked binary, eliminating the need for shared libraries on the target environment.
While both options individually contribute to creating static binaries, they serve different purposes:
Without -ldflags '-extldflags "-static"', even if CGO is disabled, the Go binary will still rely on shared Go libraries, causing the "no such file or directory" error in scratch-based Docker images. Therefore, using both flags is crucial for creating truly static binaries that are independent of the target environment's libraries.
The above is the detailed content of Why are both `CGO_ENABLED=0` and `-ldflags \'-extldflags \'-static\'\'` necessary for creating static Go binaries?. For more information, please follow other related articles on the PHP Chinese website!