C++ – static-libgcc and static-libstdc++ not working

cgccstatic-libraries

I try to compile projects with -static -static-libgcc -static-libstdc++ in order to have libraries statically linked. However, exec is compiled with dynamically linked libraries. I try to reinstall gcc and g++ but it doesn't help. It's rather my local environment fault, because on other's machines it is linked statically.

ELF 64-bit LSB  executable, x86-64, version 1 (GNU/Linux), 
dynamically linked (uses shared libs), for GNU/Linux 2.6.24, 
BuildID[sha1]=, not stripped

I have Ubuntu 14.10, gcc version 4.8.4

Thank You

Best Answer

I just had the same problem. The best explanation I was able to find was this:

On a side note, your linker could be picking up a dynamic (*.so) library that prevents -static-libstdc++ and -static-libgcc to be used. Every library calling libgcc and libstdc++ should be linked statically (if there is a static version available, of course). https://stackoverflow.com/a/18263911/399105

Digging even further, it also seems that statically linking glibc (which gcc uses by default) may not be a good idea either, and there are better alternatives such as uClibc and musl libc.

Between the two, musl seemed to be more recently maintained, so that's what I went with. I was finally able to build a fully static binary by first building musl statically:

./configure --disable-shared --enable-wrapper=gcc && make && sudo make install

And then using musl to build the other software statically:

CC="/usr/local/musl/bin/musl-gcc" LDFLAGS="-static" ./configure

If you want more details, you can see exactly what I was doing here: https://github.com/bmaupin/openldap-tools-static/blob/master/build.sh