Create statically-linked binary that uses getaddrinfo?
Solution 1
glibc uses libnss to support a number of different providers for address resolution services. Unfortunately, you cannot statically link libnss, as exactly what providers it loads depends on the local system's configuration.
Solution 2
I found a solution: you can use musl library to replace glibc. To use musl, you can either install it and build your software using musl-gcc, or you can use a Linux distribution that uses musl, e.g. Alpine Linux.
In my case, to save time, I chose Alpine Linux to build my program (https://github.com/zhanxw/rvtests), as I don't want to build multiple compilers (gcc, g++ and gfortran).
Solution 3
I think certain features are dependent on the dynamic loader to work things out at run time. static linking is no longer practical unfortunately http://people.redhat.com/drepper/no_static_linking.html
Neeladri Vishweswaran
I am a student at the Indian Institute of Science.
Updated on July 24, 2020Comments
-
Neeladri Vishweswaran almost 4 years
I have included the header
netdb.h
, wheregetaddrinfo
is included, but gcc issues this warning:warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking gcc -m32 -static -s -O2 -std=c99 -D_POSIX_C_SOURCE=200112L myprogram.c
How can I statically compile whatever file is missing ?
Possible solutions:
It could be that the glibc installation is missing the corresponding object file necessary for static compilation. If that is the case, create the corresponding object file and link it at compilation.
Try EGLIBC instead of glibc.
I succesfully compiled my program with dietlibc which compiled without any errors plus the resulting binary was much smaller than what glibc makes.
-
Neeladri Vishweswaran about 14 yearsI think it depends on what you need to do. Static compiling is a valid solution if binary-portability is a must.
-
pixelbeat about 14 yearsWell the above mentions that some things are not possible if you statically link. I've some notes on binary compatibility here: pixelbeat.org/programming/linux_binary_compatibility.html
-
Kalle Richter over 9 yearsMeanwhile in version 2.20 there is the
--enable-static-nss
flag ofconfigure
which seems to do exactly this. Note that static linking introduces some disadvantages (see @pixelbeat's answer and the comments made to it). -
zhanxw about 8 yearsI found a solution that uses musl instead of glibc. See my answer below: stackoverflow.com/a/37245653/425758
-
JC1 over 6 yearsDo you know of a solution for C++?
-
JC1 over 6 yearsThanks. Do you know if binaries compiled in Alpine are portable? I am building a binary to run as a lambda on Amazon AWS and I think compiling it on CentOS (the OS used for lambdas) is highly recommended.
-
zhanxw over 6 years@JC1 Yes, I compiled on Alpine Linux and can run it on Ubuntu 16.04 and CentOS7.