Loading a Linux Library from a different path – LD_PRELOAD

During the course of development, sometimes one needs to load a specific library from a specific path instead of the stock library that comes installed with the linux operating system. In such cases, LD_PRELOAD is a useful tool.

For example, my Ubuntu 14.04 laptop has the Bluez (linux bluetooth stack) version 4.101-0ubuntu13 installed by default. Thats a pretty old one. Since I wanted to use a newer version of the library for a project of mine and I didn’t want to overwrite my stock library, I installed the newer version (5.19) in a dedicated directory i.e. /home/pratik/Developer/CL/bluez-5.19-install. As a result, the newer version of the library resided at /home/pratik/Developer/CL/bluez-5.19-install/lib/libbluetooth.so.3. So now how do I explicity make a binary which is dependent on the bluetooth library use the one installed at the above mentioned location?

Trick is to use LD_PRELOAD. For eg. If I’m running a program called ‘a-bluetooth-program’ and I want to run it against the new library, this is what I do.

LD_PRELOAD=/home/pratik/Developer/CL/bluez-5.19-install/lib/libbluetooth.so.3 a-bluetooth-program

How do I know the trick is working? Of course by using ldd.

@$ LD_PRELOAD=/home/pratik/Developer/CloudLeaf/bluez-5.19-install/lib/libbluetooth.so.3 ldd st
	linux-vdso.so.1 =>  (0x00007fffe1ee9000)
	/home/pratik/Developer/CloudLeaf/bluez-5.19-install/lib/libbluetooth.so.3 (0x00007f1b5286f000)
	libncurses.so.5 => /lib/x86_64-linux-gnu/libncurses.so.5 (0x00007f1b52628000)
	libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f1b523fe000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1b52038000)
	libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f1b51e34000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f1b52a90000)

If you look at the output of ldd command which is used to print the shared libraries required by a command, you will see that st is now linking to the newer version of the library.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.