是否可以从代码中获取依赖库的位置
Is it possible to get location of dependent libraries from within code
我想使用 dlopen 函数从我的程序中加载一些依赖库。是否有可能知道这些图书馆的实际位置?
例如,ldd 显示系统中具有路径的所有依赖库。它是如何工作的?是否有可能通过我的 C++ 代码中的某些调用获取我需要使用 dlopen 加载的相应库的路径?
从man dlopen
可以读到:
The function dlopen() loads the dynamic library file named by the null-terminated string filename and returns an opaque "handle" for the dynamic library. If filename is NULL, then the returned handle is for the main program. If filename contains a slash ("/"), then it is interpreted as a (relative or absolute) pathname. Otherwise, the dynamic linker searches for the library as follows (see ld.so(8) for further details):
(ELF only) If the executable file for the calling program contains a DT_RPATH tag, and does not contain a DT_RUNPATH tag, then the directories listed in the DT_RPATH tag are searched.
If, at the time that the program was started, the environment variable LD_LIBRARY_PATH
was defined to contain a colon-separated list of directories, then these are searched. (As a security measure this variable is ignored for set-user-ID and set-group-ID programs.)
(ELF only) If the executable file for the calling program contains a DT_RUNPATH tag, then the directories listed in that tag are searched.
The cache file /etc/ld.so.cache
(maintained by ldconfig(8)) is checked to see whether it contains an entry for filename.
The directories /lib
and /usr/lib
are searched (in that order).
因此,如果所需的库已“安装”,一个简单的 dlopen("foobar.so", flag)
即可。
我想使用 dlopen 函数从我的程序中加载一些依赖库。是否有可能知道这些图书馆的实际位置?
例如,ldd 显示系统中具有路径的所有依赖库。它是如何工作的?是否有可能通过我的 C++ 代码中的某些调用获取我需要使用 dlopen 加载的相应库的路径?
从man dlopen
可以读到:
The function dlopen() loads the dynamic library file named by the null-terminated string filename and returns an opaque "handle" for the dynamic library. If filename is NULL, then the returned handle is for the main program. If filename contains a slash ("/"), then it is interpreted as a (relative or absolute) pathname. Otherwise, the dynamic linker searches for the library as follows (see ld.so(8) for further details):
(ELF only) If the executable file for the calling program contains a DT_RPATH tag, and does not contain a DT_RUNPATH tag, then the directories listed in the DT_RPATH tag are searched.
If, at the time that the program was started, the environment variable
LD_LIBRARY_PATH
was defined to contain a colon-separated list of directories, then these are searched. (As a security measure this variable is ignored for set-user-ID and set-group-ID programs.)(ELF only) If the executable file for the calling program contains a DT_RUNPATH tag, then the directories listed in that tag are searched.
The cache file
/etc/ld.so.cache
(maintained by ldconfig(8)) is checked to see whether it contains an entry for filename.The directories
/lib
and/usr/lib
are searched (in that order).
因此,如果所需的库已“安装”,一个简单的 dlopen("foobar.so", flag)
即可。