从静态库中提取目标文件,然后生成动态库

从静态库中提取目标文件,然后生成动态库
-fPIC
If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global
offset table.

frank@ubuntu:~/test/trunk/libc/gcc/sharelib$ gcc -shared -fPIC -o libhelp.so help.o
/usr/bin/ld: help.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
help.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

原因是 生成help.o文件时,没有加上-fPIC参数.这种情况下需要重新编译help.o并带上-fPIC参数,前提是你有help.c的源码.
当然如果libhelp.a是第三方提供,提取help.o文件后,发现第三方编译help.o时,并没有使用-fPIC参数,那么就不能使用这个help.o文件生成动态库.

./main_shared: error while loading shared libraries: libhelo.so: cannot open shared object file: No such file or directory
找不到动态库一般有两种情况:

  1. 你的平台运行环境中确实是没有该动态库;(遇到这种情况将动态库安装即可)

  2. 可执行程序运行调用该动态库时,按照默认动态库搜索路径找不到该文件;
    显然,我们这里的情况属于第2种;
    一般动态库的默认搜索路径是:/lib或/usr/lib
    解决办法:

  3. 将动态库放置默认搜索路径(/lib或/usr/lib);

  4. export LD_LIBRARY_PATH
    我们的例子中
    export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

  5. 也可以使用ldconfig.

     主要是在默认搜寻目录(/lib和/usr/lib)以及动态库配置文件/etc/ld.so.conf内所列的目录下, 搜索出可共享的动态链接库(格式如lib*.so*), 进而创建出动态装入程序(ld.so)所需的连接和缓存文件. 缓存文件默认为/etc/ld.so.cache, 此文件保存已排好序的动态链接库名字列表. 
     一般/etc/ld.so.conf文件的内容是include /etc/ld.so.conf.d/*.conf,即可支持自定义指定动态库加载路径而不影响默认配置。
原文地址:https://www.cnblogs.com/black-mamba/p/9687439.html