Rules of static linking: libstdc++, libc, libgcc
When can I link?
  1. Statically linking to libstdc++ is fine. Optional, and harmless (unless you’re using a system library written in C++; very rare indeed on unix). And, sometimes is necessary if producing binaries to run on systems with different versions of libstdc++ (or none). Therefore, I always statically link to libstdc++. It’s the only way to target Ubuntu 6 to 12.04 and RHEL 2 to RHEL 6 with a single binary (those are probably the oldest versions it’s worth compiling for).
  2. Statically linking to libc: never ever do this. One exception only: the entire binary is statically linked, and never uses dlopen to load anything at runtime either.
  3. Statically linking to libgcc: Depends on the system. Never ever do this on a GNU-based system (ie a system that ships with libgcc or gcc, or where libc was compiled with gcc, or where libc is glibc, etc). Never ever do this if loading a shared library (runtime or loadtime) that was compiled with gcc by someone else (don’t break the rules unless you know what you’re doing!). Do do this on systems without libgcc (eg Solaris). Try not to ship binaries that rely on a particular version of some library that the OS doesn’t provide! This relies on you not loading any external C++ libraries (statically or dynamically), except for shared objects you’ve carefully made yourself!
How do I link?
  1. To statically link libstdc++: in each directory where you build binaries (or shared objects), have your makefiles do ln -s `g++ $(CXXFLAGS) -print-file-name=libstdc++.a` libstdc++.a. Then, add -L. to your commandline. If you only use recent versions of GCC, there’s a -shared-libstc++ option.
  2. Don’t statically link libc!
  3. GCC 2 doesn’t add a libgcc dependency by default (on platforms that don’t have it). Nothing to worry about. GCC 3: use the -static-libgcc option if it’s needed (it won’t be needed for example if you compiled gcc with --disable-shared).

Google if you need an explanation for any of the above. The issues are somewhat subtle for a few cases.