Static vs dynamic linking

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the compilers category.

Last Updated: 2024-03-02

What is static linking?

The necessary library functions are embedded directly in the program's executable binary file. Said to be "statically linked" to its libraries.

What is dynamic linking?

Uses shared libraries.

How it works? The program contains (statically linked) code called when the program starts. This gets the link library to determine all the dynamic libraries which the program requires are located, along with the names of the variables and functions needed from those libraries. Then the libraries are mapped into memory, making their functionality available via symbol resolution.

After this, it maps the libraries into the middle of virtual memory and resolves the references to the symbols contained in those libraries.

Examples of dynamic libraries: .so in Linux and .dll in Windows

Static advantages

Dynamic advantages

Which is faster?

"Classically, dynamic libraries require a some kind of glue layer which often means double dispatch or an extra layer of indirection in function addressing and can cost a little speed (but is function calling time actually a big part of your running time???). However, if you are running multiple processes which all call the same library a lot, you can end up saving cache lines (and thus winning on running performance) when using dynamic linking relative to using static linking. (Unless modern OS's are smart enough to notice identical segments in statically linked binaries. Seems hard, anyone know?)" -