Search code examples
language-agnosticlinkerloader

Why are static and dynamic linkable libraries different?


If both of them contain compiled code, why can't we load the "static" files at runtime and why can't we link with the dynamic libraries at compile time? Why is there a need for separate formats to contain "standalone" code? What needs to be stored in either one that warrants the difference?


Solution

  • Static libraries are true libraries in the sense that they contain a library of object files. Each object file is often created from a single source file and contains machine code as well as information about data required for the code. During the link step the linker will pick the necessary object files and combine them into an executable.

    One important part of machine code is that jumps, calls and data pointers will have to contain real memory addresses. However, if an object file needs to call another function in another object file it can only refer to that function using a symbol. When the linker combines the object files into executable code the symbol references are resolved and turned into real memory addresses.

    A dynamic library is executable code that can be loaded into the memory and executed straight away. On some operating systems there may be an additional step where the code is rebased by moving the executable code to another location and this requires all absolute addresses within the code to be shifted by a fixed amount. This operation is still much faster than combining object files and resolving symbols done by the linker.

    To sum it up:

    • Static libraries contain pieces of executable code that uses symbols to refer to other pieces of executable code
    • Dynamic libraries (and executables) contain executable code now placed at fixed locations enabling the symbols to be replaced with real memory addresses

    If you've ever tried to link a reasonably sized project you will have noticed that it takes a non-trivial amount of time, probably longer than you would like to wait to start an application. That sort of explains why you can't execute static libraries. And dynamic libraries have been optimized and stripped to not contain anything except executable code which makes them unsuitable for use as static libraries.