Linking shared libraries: overcoming runtime errors

Say you’re developing a program in C++ and you need to use some exotic library called libAAA.
You have been able to download the sources and build the package ( by adding -I/path/to/the/library/include to the compilation options, for example) and linking it ( by adding something like -L/path/to/the/library/lib -lAAA to the linker options, for example).

But running the program raises an error:
./program_a: error while loading shared libraries: cannot open shared object file: No such file or directory

This is due to the fact that although you have informed the compiler and the linker about the location of your libAAA files, the system cannot find them at runtime. In fact, the program_a would call a dynamic linker that searches for shared libraries in the system. It, however, searches only in default locations where libraries are commonly installed (such as /usr/lib).

You can check the dynamic libraries by invoking ldd command on the executable:
>>ldd program_a => (0xb7f48000) => /usr/lib/ (0xb7836000) => not found => /usr/lib/ (0xb76c4000)
/lib/ (0xb7f49000)

Here it is clearly seen that the linker cannot find the library. A remedy is to add the custom library path to the LD_LIBRARY_PATH environment variable (this example is for bash shell):
>>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/the/library/lib

Now the library can be located at runtime:
>>ldd program_a => (0xb7f48000) => /usr/lib/ (0xb7836000) => /path/to/the/library/lib/ (0xb77da000) => /usr/lib/ (0xb76c4000)
/lib/ (0xb7f49000)

Another option is to do a manual system-wide install by copying the library to /usr/lib, for example, or modifying the dynamic linker look-up path (in file /etc/ Naturally such problems should not appear if the library is well-built so that make install will do a system-wide installation automatically.

More information can be found in here for instance.


One Response to “Linking shared libraries: overcoming runtime errors”

  1. name Says:

    Thanks a lot,
    this article way very helpful.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s