Course contentsShow
← Linux
Lesson 269 of 1,8193. The Filesystem Hierarchy and POSIX StandardsFree lesson

Library Search Paths and Dynamic Loading

Troubleshoot shared library dependencies using linker search paths and standard system directories.

In this lesson, you will learn how the Linux system locates and loads the shared libraries required by your programs to function correctly.

When you execute a binary, it often doesn't contain all the code it needs to run. Instead, it relies on shared libraries—files ending in .so (shared object)—that reside elsewhere on your filesystem. If you have ever seen an error like error while loading shared libraries: libexample.so.1: cannot open shared object file, it means the system couldn't find a necessary piece of code.

The Search Hierarchy

When a program starts, a special component called the dynamic linker (often ld.so) takes over to find these dependencies. It searches in a specific, prioritized order:

  1. DT_RPATH/DT_RUNPATH: Some binaries have a hard-coded path embedded within them, telling the linker exactly where to look first.
  2. LD_LIBRARY_PATH: This is an environment variable you can set to tell the linker to check specific directories before the standard system locations. This is useful for testing new versions of a library without installing them system-wide.
  3. /etc/ld.so.cache: For performance, the system keeps a pre-compiled list of library locations in this file. The ldconfig utility updates this cache based on configuration files found in /etc/ld.so.conf.
  4. Default System Paths: Finally, it searches the standard, trusted directories, primarily /lib and /usr/lib.

Troubleshooting Example

If you move a library file or install a custom one, the linker might lose track of it. You can see exactly what libraries a binary is looking for by using the ldd command:

ldd /usr/bin/cat

This will print a list of every library the cat command needs and where the system currently finds them. If you see not found next to a library name, the linker cannot locate the file in any of its search paths. You can fix this by ensuring the library is in a standard directory or by updating your library configuration files.

Key Takeaway: The dynamic linker resolves dependencies by checking embedded paths, user-defined environment variables, and a system-wide cache, falling back to standard directories like /lib and /usr/lib.