Dynamic Libraries
Over the past few months, Iâve run into dynamic libraries several times while working on side projects, but I never really stopped to understand what they are or how they work. After getting stuck in similar situations more than once, I finally took some time to learn the basics. Different operating systems follow different conventions (.so in Linux, .dylib in macOS, and .dll in Windows), but Iâll stick to Linux here.
In C and C++, each source file (.c) is compiled to an object file (.o). Multiple object files can then be bundled together as a library. For a static library, this is essentially an archive of .o files plus an index that helps the linker find symbols efficiently. Dynamic libraries are structured differently, but the same high-level idea still applies.
Letâs say we have a library called libfoo. libfoo bundles two source files, foo.c and foo_utils.c. We also have app.c, an application that uses libfoo.
Static Libraries
Section titled âStatic LibrariesâHere is how we can create a static library (libfoo.a).
# compile each .c to .ogcc -c foo.c -o foo.ogcc -c foo_utils.c -o foo_utils.o
# create a static libraryar rcs libfoo.a foo.o foo_utils.oNow, the library is ready to be linked against application code.
# compile application codegcc -c app.c -o app.o
# link libfoogcc app.o -o exe -L . -lfoo./exeFor static libraries, the linker checks which symbols app.o needs from libfoo.a, pulls in the relevant object files, and copies the library code into the final executable. The final executable ends up actually containing parts of the library.
This has a few implications. First, there is no runtime dependency. Once the executable is built, it can run without libfoo.a being present. Deployment is simple since the required library code is already included in the executable. But this also means that library updates wonât affect the program unless it is rebuilt or relinked, and the executable grows because it contains library code.
One thing to note here is that the location of libfoo.a matters. In the example above, -L . tells the linker to search the current directory as well. If we omitted it, the linker would search default library paths such as /usr/local/lib.
Where libfoo.a is located is perhaps less important for static libraries because once the executable has been built, we no longer need the library unless we want to link the executable again. As we will see, with dynamic libraries, we have to be more careful about where libfoo.so is located because it needs to be located reliably at runtime.
Dynamic Libraries
Section titled âDynamic LibrariesâBefore we go over the commands to create and link against dynamic libraries, letâs compare them with static libraries at a high level.
A dynamic library, also called a shared object on Linux, isnât copied into your executable. Instead, the executable simply keeps references like âI need these symbols from this library.â The library is loaded later at runtime.
This usually makes the executable smaller, but also means the executable depends on the right libraries being available at runtime. The âsharedâ part is literal; multiple processes can map to the same read-only library code in physical memory. This is reasonable because many programs rely on the same routines, such as malloc from the C standard library.
If a library is updated, programs can pick up the new version without a rebuild, which is useful for bug fixes. However, this can also cause a headache if the new version is not compatible with what the program expects.
To create a dynamic library:
# compile each .c to .ogcc -c -fPIC foo.c -o foo.ogcc -c -fPIC foo_utils.c -o foo_utils.o
# create a dynamic librarygcc foo.o foo_utils.o -shared -o libfoo.soNote that when we compile foo.c and foo_utils.c, we include the -fPIC flag. Here, PIC stands for âPosition Independent Codeâ. At a high-level, this tells the compiler to generate assembly instructions that can be loaded into different regions of the virtual address space. For example, the compiler might prefer using relative addresses than absolute addresses, since we donât know where the library code will be loaded to.
Once we have built libfoo.so, we can put it in an expected location, such as /usr/local/lib, and run sudo ldconfig to update the dynamic linkerâs library cache. It is also possible to keep libfoo.so in another location and tell the linker and loader where to find it. Finally, we can link against libfoo.so.
gcc -c app.c -o app.ogcc app.o -o exe -lfoo./exeWhat happens at runtime?
Section titled âWhat happens at runtime?âLetâs pause to think about how dynamic libraries are loaded at runtime, which brings up two different questions: how does the loader locate libfoo.so, and what happens once libfoo.so is found?
The loader is responsible for preparing a program to run. It maps the executable and its required libraries into the processâs virtual address space and resolves symbols from dynamic libraries.
As I touched on before, the loader searches configured library paths, such as /usr/lib, to locate the required .so file. It is also possible to add additional search locations, such as the current working directory, using LD_LIBRARY_PATH. The takeaway is that we have to make sure the loader can reliably locate libfoo.so at runtime.
Once the loader has located libfoo.so, it maps the library into the applicationâs virtual address space. The library does not necessarily have to be loaded into physical memory all at once; pages can be brought into RAM as they are needed, and read-only code pages may be shared with other processes. The loader also resolves the symbols required by the application so that function calls and data references point to the correct runtime addresses.
Helpful Commands
Section titled âHelpful CommandsâHere are some bash commands that might be handy.
First, ldd shows which shared libraries the executable depends on and where they are being resolved from.
> ldd ./exe
libfoo.so => /usr/local/lib/libfoo.solibc.so.6 => /usr/lib/libc.so.6You can also inspect what the executable itself records as dependencies:
> readelf -d ./exe
NEEDED Shared library: [libfoo.so]NEEDED Shared library: [libc.so.6]This tells you what library names are recorded in the binary, while ldd tells you what those dependencies resolve to on the current system.
Last but not least, nm can be used to examine which dynamic symbols a library exposes.
nm -D libfoo.soSymbol Interposition
Section titled âSymbol InterpositionâLetâs say we implemented a custom memory allocator library. Whereas libfoo.so defined new symbols that did not conflict with symbols from other system libraries, malloc from libmymalloc.so needs to replace the systemâs default malloc. In this case, we have to be more careful about how the symbols are resolved.
The loader typically uses the first matching symbol it finds during symbol lookup. This means the lookup order matters, and we are not automatically guaranteed that malloc from libmymalloc.so will override the systemâs default memory allocator.
To ensure that malloc from libmymalloc.so is used, we can use LD_PRELOAD to load libmymalloc.so before the programâs normal shared-library dependencies. This means there can be multiple definitions of malloc in the same virtual address space. However, since symbol lookup uses the first matching definition, malloc from libmymalloc.so takes precedence.
This is interesting because we might expect symbol collisions to be illegal. That is mostly true when linking an ordinary program: if the linker finds multiple conflicting definitions of the same symbol, it will usually report an error. With dynamic libraries, multiple definitions can coexist in the processâs virtual address space at runtime, and the loaderâs symbol lookup rules determine which one is used.
LD_PRELOAD=./libmymalloc.so ./exeIn this article, I covered the difference between static and dynamic libraries. Having a basic mental model of linking and loading has made it easier for me to build projects from source and debug weird âmissing symbol / wrong versionâ issues, and hopefully itâll save me from repeating the same mistakes in the future.