Static Linking – Best Practices for libstdc++ and libgcc in Linux

cdistributionlinkinglinuxstatic-linking

Context: I have an open source project which uses JNI. While it's possible to build it yourself, I expect most users will use standard Java tools like Maven, Gradle, or SBT to download the JAR, which contains the pre-compiled binary image. This is no problem on Windows, but on Linux it gets complex.

I'm wondering how much to statically link when creating these packages so it's compatible with most Linux distributions. I know that, for example, Alpine Linux does not come with libstdc++, meaning that it would fail when in a small docker container.

There's also the possibility of older versions. For example, a quick look at nm suggests it's linking _ZNSt11logic_errorC1EPKc@@GLIBCXX_3.4.21 and __vsnprintf_chk@@GLIBC_2.3.4. What if the host has versions older than 3.4.21 and 2.3.4?

However, most literature I've seen tells me not to link against libgcc. Is that still true? Is it the same if I switch to clang (which has its own standard libs?)

Best Answer

Static linking glibc is a no-no. My understanding is that is often customized for the distro, so you don't want to be distributing that to machines running different linux distros/releases. There are drop-in replacements for it that you can statically link, like MUSL. I've never tried them, so the rest in that regard is left up to the reader. Static linking everything else should be fine.

One approach I've used very successfully is to build your binary on an old Linux release (including doing static linking where you can). Those binaries will be forward compatible. So you should be able to get yourself some assurance that your binary will run on most distros from the past decade (though as you point out, Alpine is different - it uses MUSL - so you may need to build on Alpine to ensure compatibility). Technically speaking you can use modern releases to target older glibc versions for compatibility, but I found just using the old release to be the simpler.

Related Topic