2.4.2. Static and dynamic linking
When building C or C++ applications, you must use dynamic linking. Static linking reduces compatibility and prevents timely library security updates.
- Comparison of static and dynamic linking
- Static linking makes libraries part of the resulting executable file. Dynamic linking keeps these libraries as separate files.
Static linking has numerous disadvantages and should be avoided, particularly for whole applications and the glibc and libstdc++ libraries:
Resource use: Static linking results in larger executable files which contain more code. Libraries contribute extra code that is not shared across programs on the system. That behavior increases file system usage and memory usage at run time. Multiple processes running the same statically linked program will still share the code.
However, static applications need fewer runtime relocations, leading to reduced startup time, and require less private resident set size (RSS) memory. Generated code for static linking can be more efficient than for dynamic linking due to the overhead introduced by position-independent code (PIC).
Security: Dynamically linked libraries that provide ABI compatibility can be updated without changing the executable files depending on these libraries. This is especially important for libraries provided by Red Hat as part of Red Hat Enterprise Linux, where Red Hat provides security updates. Static linking against any such libraries is strongly discouraged.
Compatibility: Static linking seems to provide executable files independent of the versions of libraries provided by the operating system. However, most libraries depend on other libraries. With static linking, this dependency becomes inflexible and as a result, both forward and backward compatibility is lost. Static linking is guaranteed to work only on the system where the executable file was built.
Applications that statically link against the GNU C library (glibc) still need glibc present on the system as a dynamic library.
Furthermore, the glibc dynamic library at run time must exactly match the version present at link time.
As a result, static linking works only on the system where you built the executable file.
Support coverage: Most static libraries provided by Red Hat are in the CodeReady Linux Builder channel and not supported by Red Hat.
Functionality: Some libraries, notably the GNU C Library (glibc), offer reduced functionality when linked statically.
For example, when statically linked, glibc does not support threads and any form of calls to the dlopen() function in the same program.
- Cases for static linking
Static linking might be a reasonable choice in some cases, such as:
- When using a library that is not enabled for dynamic linking.
-
When fully static linking is required for running code in an empty chroot environment or container. However, static linking by using the
glibc-staticpackage is not supported by Red Hat.