How to Dynamic Load The Library with Same Name But in Different Directory in Linux

How do I get dynamic libraries to load from the same directory in Ubuntu?

Antons answer: if it's your program, you can use ld's -rpath (gcc's -Wl,-rpath) to modify library search path for it. (Not that it doesn't feel like a hack too). Or you can install a script starting the program with LD_LIBRARY_PATH. Or you can put the libraries where they are searched by default.

How to force .so dependency to be in same directory as library

The .dynamic section of an ELF file (.so libraries on Linux use ELF format) contains information to help the library find its dependencies. .dynamic entries with type DT_NEEDED contain the names of other .so files for the dynamic linker to find, but they do not contain any information on where to find those files. For that, as you mentioned, you can use LD_LIBRARY_PATH, but the ELF format also provides a way to specify it in the file itself.

A .dynamic entry with type DT_RUNPATH gives the dynamic linker a path to a directory where the dynamic linker should look for DT_NEEDED files. DT_RUNPATH allows a special variable, $ORIGIN, which refers to the file's current directory. This allows you to use relative paths, without requiring the user to invoke an executable from a specific working directory.

You use the -rpath linker flag to specify a DT_RUNPATH entry. In order to pass the literal string $ORIGIN, however, you must wrap it in single quotes to prevent your shell from interpreting it as an environment variable.

Assuming you are using gcc, you should use add this argument to the link step:

-Wl,-rpath,'$ORIGIN'

Can a process load two DLLs with exactly the same name?

From the documentation (emphasis mine):

Desktop applications can control the location from which a DLL is loaded by specifying a full path, using DLL redirection, or by using a manifest. If none of these methods are used, the system searches for the DLL at load time as described in this section.

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.

So, the clause you're worried about doesn't apply when a full path is provided.



Related Topics



Leave a reply



Submit