Skip to content

Instantly share code, notes, and snippets.

@zmb3
Created October 5, 2020 15:45
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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://www.musl-libc.org/releases/musl-1.2.0.tar.gz && \
   tar -zf musl-1.2.0.tar.gz && \
   cd musl-1.2.0 && \
   ./configure --enable-static --disable-shared && \
   make && make install

Then to build your progam:

CGO_ENABLED=1 CC=musl-gcc go build --ldflags 'linkmode external -extldflags "-static"'
@Job79
Copy link

Job79 commented Aug 18, 2022

Command should be:

CGO_ENABLED=1 CC=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