Static binary with c lib dep. Is it possible?

107 views
Skip to first unread message

Marcondes Viana de Oliveira Junior

unread,
Jun 21, 2023, 3:27:34 PM6/21/23
to golang-nuts
Hi all, I’m trying to create a static binary (no external deps) for linux, on linux, using libwebp as dep.

webp.go
=======
...
/*
 #cgo pkg-config: libwebp
 #include <webp/encode.h>
 #include <stdlib.h>
...
*/

import "C"
...
=======
And I wand to generate a static linked bin.

If I use CGO_ENABLED=0
=======
... build constraints exclude all Go files in ...
=======

If I use
=======
go build -o bin/api \
    -ldflags -extldflags=-static \
    ...
=======
A giant error comes:
=======
...
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: /tmp/go-link-3823308014/000004.o: in function `_cgo_cbcce81e6342_C2func_getaddrinfo':
/tmp/go-build/cgo-gcc-prolog:58: warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
...
=======

If I just run go build, it compiles and run perfectly but
=======
$ ldd bin/api | wc -l
7
=======

I’m not sure if is it even possible, but is there something that can be done?

Ian Lance Taylor

unread,
Jun 21, 2023, 3:49:22 PM6/21/23
to Marcondes Viana de Oliveira Junior, golang-nuts
If you can build a C program statically with that library, then you
can build a Go program statically. But in general glibc does not like
to be linked statically, and that is what you are running into with
the getaddrinfo warning. You could consider using an alternative C
library like musl.

Ian

Marcondes Viana de Oliveira Junior

unread,
Jun 21, 2023, 3:54:49 PM6/21/23
to golang-nuts
Thanks Ian, got it.
Reply all
Reply to author
Forward
0 new messages