共享库
什么是共享库?
共享库是目标代码已被编译并通常分组为单个文件(库)的区域。在许多情况下,可以删除多个应用程序可以共享的代码,并将其编译到共享区域中。通常,共有两种类型的共享库:
静态库
静态链接的程序往往会变得很大,因为它们包括链接到其中的所有库函数的可执行文件。当当前正在运行的其他程序包含相同的库函数时,静态链接程序通常会使用更多的内存。静态链接库由扩展名.a标识。为了避免使用静态库遇到的一些问题,许多程序将使用所谓的动态链接库。
动态库
动态链接库允许多个程序在内存中共享相同的库代码,从而减少了内存占用。动态链接的库在多个程序之间共享。术语共享库通常涉及动态链接的库。动态库的扩展名为.so
显示共享库依赖关系
ldd命令可用于打印每个程序所需的共享库或命令上指定的共享库。
ldd命令
ldd示例:
ls001a:/usr/lib # ldd /bin/bash
linux-vdso.so.1 => (0x00007fffe35eb000)
libreadline.so.5 => /lib64/libreadline.so.5 (0x00007fc30e349000)
libdl.so.2 => /lib64/libdl.so.2 (0x00007fc30e145000)
libc.so.6 => /lib64/libc.so.6 (0x00007fc30ddd0000)
libncurses.so.5 => /lib64/libncurses.so.5 (0x00007fc30db88000)
/lib64/ld-linux-x86-64.so.2 (0x00007fc30e5bd000)
语法:ldd [OPTION]... FILE...
OPTIONS
--version
Print the version number of ldd.
-v --verbose
Print all information, including, for example, symbol versioning information.
-u --unused
Print unused direct dependencies. (Since glibc 2.3.4.)
-d --data-relocs
Perform relocations and report any missing objects (ELF only).
-r --function-relocs
Perform relocations for both data objects and functions, and report any missing objects or functions (ELF only).
--help Usage information.
链接共享库
动态链接的可执行文件在运行时通过共享对象动态链接程序ld.so进行检查。ld.so检查可执行文件中的任何依赖项,然后尝试满足这些要求。如果ld.so无法满足这些依赖性,则可执行文件将失败。
共享库路径
为了使可执行文件在运行时找到要链接的必需库,必须对系统进行配置,以便可以找到这些库。有几种方法可以实现:
/etc/ld.so.conf
将您的库目录放到/etc/ld.so.conf中。然后用root执行ldconfig命令以完成该过程。
LD_LIBRARY_PATH
使用环境变量LD_LIBRARY_PATH指向包含共享库的目录路径。可以添加多个目录,并用冒号:分隔。
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/lib ; export LD_LIBRARY_PATH
可以将此项添加到主目录中的.bashrc文件中。
使用ldconfig命令
ldconfig用于配置动态链接程序运行时绑定。ldconfig创建必要的链接,并缓存到从命令行指定的目录,/ etc / ld.so.conf文件以及受信任目录(/ lib和/ usr / lib)中找到的最新共享库。运行时链接程序ld.so使用此缓存。对文件/etc/ld.so.conf进行任何更改时,必须运行ldconfig。这将刷新目录的缓存。
ldconfig的常用选项
OPTIONS
-v Verbose mode. Print current version number, the name of each directory as it is scanned, and any links that are
created. Overrides quiet mode.
-n Only process directories specified on the command line. Dont process the trusted directories (/lib and /usr/lib)
nor those specified in /etc/ld.so.conf. Implies -N.
-N Dont rebuild the cache. Unless -X is also specified, links are still updated.
-X Dont update links. Unless -N is also specified, the cache is still rebuilt.
-f conf
Use conf instead of /etc/ld.so.conf.
-C cache
Use cache instead of /etc/ld.so.cache.
-r root
Change to and use root as the root directory.
-l Library mode. Manually link individual libraries. Intended for use by experts only.
-p Print the lists of directories and candidate libraries stored in the current cache.
与ldconfig命令关联的文件
/lib/ld.so
运行时链接程序/加载程序
/etc/ld.so.conf
包含冒号,空格,制表符,换行符或逗号分隔目录的列表的文件,在这些目录中搜索库。
/etc/ld.so.cache
文件包含在/etc/ld.so.conf中指定的目录中找到的库的有序列表。

