$ nm -g libtest.so 0000000000000670 T add 0000000000201030 B __bss_start w __cxa_finalize@@GLIBC_2.2.5 0000000000201030 D _edata 0000000000201038 B _end 0000000000000684 T _fini w __gmon_start__ 0000000000000540 T _init w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w _Jv_RegisterClasses
三、使用动态库
1. 隐式链接(编译时链接)
编写主程序main.c:
1 2 3 4 5
#include <stdio.h>#include "so.h"
int main(int argc, char *argv[]){ printf("%d\n", add(1, 2)); return 0;}
使用gcc main.c -L. -ltest -o test进行编译。
-L:添加库文件的搜索路径
-l:指定需要链接的库。该名称是处在头lib和后缀.so中的名称,如上动态库libtest.so的l参数为-l test
此时通过readelf test -d已经能看到生成的可执行文件test的Dynamic section里依赖libtest.so了
1 2 3 4 5 6 7 8
$ readelf test -d
Dynamic section at offset 0xe18 contains 25 entries: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libtest.so] 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] ......
dynamic symbols中也有一个undefined symbol(add)
1 2 3 4 5 6 7 8 9 10 11 12
$ nm -D test U add 0000000000601048 B __bss_start 0000000000601048 D _edata 0000000000601050 B _end 00000000004007b4 T _fini w __gmon_start__ 0000000000400578 T _init w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w _Jv_RegisterClasses U __libc_start_main U printf
Dynamic section at offset 0xe18 contains 25 entries: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libdl.so.2] 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] ......
dyn_test的dynamic symbols中也没有add:
1 2 3 4 5 6 7 8 9 10 11
$ nm -D dyn_test U dlerror U dlopen U dlsym w __gmon_start__ w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w _Jv_RegisterClasses U __libc_start_main U printf U puts