Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1521330
  • 博文数量: 290
  • 博客积分: 3468
  • 博客等级: 中校
  • 技术积分: 3461
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 22:21
文章分类

全部博文(290)

文章存档

2016年(13)

2015年(3)

2014年(42)

2013年(67)

2012年(90)

2011年(75)

分类: LINUX

2011-12-08 16:47:24

原文链接:GNU/Linux下库机制笔记

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
    #include

    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 #读出共享库的符号

阅读(1002) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~