GNU/Linux下库机制笔记

本文介绍如何在GNU/Linux环境下创建和使用静态及动态共享库。详细步骤包括使用GCC编译器创建共享库,通过不同方式加载共享库,以及调试技巧。此外还介绍了如何利用环境变量控制动态库的行为。


1. 创建静态库:
     gcc -c hello.c -o hello.o
     ar rcs libhello.a hello.o

2. 使用静态库:
     gcc -o test test.c -static -L. -lhello


3. 共享库版本: version.minor.release


4. 构建动态共享库:

  gcc/g++下加 -fPIC -shared 参数即可

  其中 -fPIC 作用于编译阶段,告诉编译器产生与位置无关代码(Position-Independent Code),
  则产生的代码中,没有绝对地址,全部使用相对地址,故而代码可以被加载器加载到内存的任意
  位置,都可以正确的执行。这正是共享库所要求的,共享库被加载时,在内存的位置不是固定的。
  可以export LD_DEBUG=files,查看每次加载共享库的实际地址。

  其中 -shared 作用于链接阶段,实际传递给链接器ld,让其添加作为共享库所需要的额外描述
  信息,去除共享库所不需的信息。

  可以分解为如下步骤:

     I. gcc -c err.c -fPIC -o err.o
     II. gcc -shared -o liberr.so.0.0 err.o

           II <==> ld -Bshareable -o liberr.so.0.0 err.o

     III. ln -s liberr.so.0.0 liberr.so



5. 动态共享库的使用:
     
  a. 由共享库加载器自动加载

     gcc -o test test.c -lerr -L. -Wl,-rpath=./

    -Wl,option
      Pass option as an option to the linker. If option contains commas,
      it is split into multiple options at the commas.

     -rpath: 指定运行时搜索动态库的路径,可以用环境变量LD_LIBRARY_PATH指定。


  b. 程序自己控制加载、符号解析(使用libc6之dl库)

    gcc cos.c -o cos -ldl

    /* cos.c */
    #include <stdio.h>
    #include <dlfcn.h>

    int main()
    {
      void *handle;
      double (*cosine)(double);
      char *error;
      double rev;

      handle = dlopen("libm.so", RTLD_LAZY); // 加载动态库
      if(!handle)
      {
          fprintf(stderr, "%s/n", dlerror());
          exit(1);
      }

      dlerror();

      cosine = dlsym(handle, "cos"); // 解析符号cos
      if((error = dlerror()) != NULL)
      {
          fprintf(stderr, "%s/n", error);
          exit(1);
      }

      rev = cosine(3.1415926); // 使用cos函数
      printf("The cos result is: %f/n", rev);

      dlclose(handle);

      return 0;
    }




6. GNU/Linux下动态库之加载器为/lib/ld-linux.so, 可执行的。

  /lib/ld-linux.so ./cos <===> ./cos


7. 有用的环境变量
     
     LD_LIBRARY_PATH

      指定运行时动态库的搜索路径

     LD_DEBUG

      调试用,其值可为:

      libs     display library search paths
      reloc     display relocation processing
      files     display progress for input file
      symbols   display symbol table processing
      bindings   display information about symbol binding
      versions   display version dependencies
      all       all previous options combined
      statistics display relocation statistics
      unused     determined unused DSOs
      help     display this help message and exit


8. 搜索含有cos函数的共享库名

     nm -AD /lib/* /usr/lib/* 2>/dev/null | grep "cos$"

     nm -- 从对象文件中列出符号。


9. 读取ELF文件格式信息

    readelf -Ds ./libfoo.so #读出共享库的符号






 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值