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
./program_a: error while loading shared libraries: libAAA.so: 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
linux-gate.so.1 => (0xb7f48000)
liblapack.so.3gf => /usr/lib/liblapack.so.3gf (0xb7836000)
libAAA.so => not found
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76c4000)
/lib/ld-linux.so.2 (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
linux-gate.so.1 => (0xb7f48000)
liblapack.so.3gf => /usr/lib/liblapack.so.3gf (0xb7836000)
libAAA.so => /path/to/the/library/lib/libAAA.so (0xb77da000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76c4000)
/lib/ld-linux.so.2 (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/ld.so.conf). 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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s