Skip to content

Instantly share code, notes, and snippets.

@zmb3
Last active September 23, 2024 17:02
Show Gist options
  • Save zmb3/2bf29397633c9c9cc5125fdaa988c8a8 to your computer and use it in GitHub Desktop.
Save zmb3/2bf29397633c9c9cc5125fdaa988c8a8 to your computer and use it in GitHub Desktop.
Compile static binaries for Go programs that leverage Cgo.

In order to compile a fully static binary when using Cgo you'll need to link in a C library like musl.

I find it convenient to have a Docker image ready for building these artifacts.

FROM golang
RUN wget https://musl.libc.org/releases/musl-1.2.5.tar.gz && \
   tar -xzf musl-1.2.5.tar.gz && \
   cd musl-1.2.5 && \
   ./configure --enable-static --disable-shared && \
   make && make install

Then to build your progam:

CGO_ENABLED=1 CC=/usr/local/musl/bin/musl-gcc go build --ldflags '-linkmode=external -extldflags=-static'
@let4be
Copy link

let4be commented Jul 13, 2023

It's also tar -zxf musl-1.2.0.tar.gz...

@Slach
Copy link

Slach commented Jul 14, 2023

on ubuntu + golang 1.20

apt-get install -y --no-install-recommends musl-dev musl-tools
CGO_ENABLED=1 CC=musl-gcc go build --ldflags '-linkmode=external -extldflags=-static' -o binary_name ./

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment