Runtime library loading and LD_LIBRARY_PATH
What you'll learn: How to tell your operating system exactly where to find shared libraries when your program starts up.
When you compile a program using a shared library (.so on Linux or .dll on Windows), the library code isn't actually inside your executable. Instead, your program carries a "shopping list" of files it needs to run. The moment you launch the app, a specialized tool called the dynamic linker rushes to find those files and plug them into your program’s memory.
The "Missing Map" Problem
Imagine you’ve hired a chef (your program) who needs a specific spice blend (the shared library). If the spice is in a standard cupboard like /usr/lib, the chef finds it instantly. But if you keep your spices in a custom wooden box in the garage, the chef will throw their hands up and quit because they don’t know where to look.
By default, the system only looks in a few standard folders. If you have built your own library and kept it in your project folder, you will likely see an error like:
error while loading shared libraries: libmymath.so: cannot open shared object file.
Using LD_LIBRARY_PATH
On Linux and macOS, the LD_LIBRARY_PATH environment variable acts as a temporary map for the dynamic linker. It tells the system: "Before you give up, check these extra folders for the libraries I need."
You don't need to change your C code to fix this. You simply set the variable in your terminal before running the program:
// Assume we compiled 'main.c' and linked it against 'libtest.so'
// The library 'libtest.so' is located in a folder called 'libs'
// 1. Try to run it (This usually fails)
// ./my_program
// 2. Set the path and run (This succeeds)
// export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/project/libs
// ./my_program
By adding your custom directory to LD_LIBRARY_PATH, the linker checks your libs folder first. This is incredibly useful during development when you are testing new versions of a library but aren't ready to install them into the system's permanent folders.
Key takeaway
LD_LIBRARY_PATH is an environment variable that tells the dynamic linker extra directories to search for shared libraries at runtime.