Home  >  Article  >  Backend Development  >  Why are both `CGO_ENABLED=0` and `-ldflags \'-extldflags \"-static\"\'` necessary for creating static Go binaries?

Why are both `CGO_ENABLED=0` and `-ldflags \'-extldflags \"-static\"\'` necessary for creating static Go binaries?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 19:53:29167browse

Why are both `CGO_ENABLED=0` and `-ldflags '-extldflags

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:

  • CGO_ENABLED=0 prevents any dependencies on external C libraries.
  • -ldflags '-extldflags "-static"' specifically links all Go-related libraries (such as runtime, math, etc.) statically.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn