动态库,静态库(生成)

来源:互联网 发布:日内瓦公约 知乎 编辑:程序博客网 时间:2024/05/30 05:14

http://www.2cto.com/kf/201203/122077.html


生成静态库:

  • gcc -c hello.c
  • ar cr libmyhello.a hello.o  ---- 生成
  • gcc -o hello main.c -L. -lmyhello  ---- 使用


生成动态库:


  • gcc -fPIC -c hello.c 

//此处必须使用-fPIC,否则执行下一条命令可能失败。如:/usr/bin/ld: hello.o: relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC hello.o: could not read symbols: Bad value           collect2: ld returned 1 exit status

 “PIC”命令行标记告诉GCC产生的代码不要包含对函数和变量具体内存位置的引用,这是因为现在还无法知道使用该消息代码的应用程序会将它连接到哪一段内存地址空间。

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.  This option makes a difference on the m68k, PowerPC and SPARC. Position-independent code requires special support, and therefore works only on certain machines.

  • gcc -shared -o libmyhello.so hello.o     -------- 生成动态库
  • gcc -o hello main.c -L. -lmyhello  --- 编译时使用

虽然此处编译成功,但执行出错

./hello: error while loading shared libraries: libmyhello.so: cannot open shared object file: No such file or directory

执行时使用的解决方法:

      • 1.可以将动态库复制到/lib或者/usr/lib下。
      • 2. 即使用-rpath增加运行时的路径。有几种方式:
        1. gcc -o hello main.c -lmyhello  -Wl,-rpath . -Wl,-L.  
        2. gcc -o hello main.c -lmyhello  -Wl,-rpath,. -Wl,-L.  
        3. gcc -o hello main.c -lmyhello  -Wl,-rpath,. -L.
          • 3..编辑/etc/ld.so.conf文件,加入库文件所在目录的路径;运行ldconfig,该命令会重建/etc/ld.so.cache文件
          • http://www.360doc.com/content/11/0225/11/5912935_95958917.shtml
                                              LD_LIBRARY_PATH=XXXXXX
                                              export   LD_LIBRARY_PATH -------- 这样再执行就可以了。

      静态库链接方法:-static 则使用静态库,所有-l后的库都优先使用静态库。而默认是先查找动态库,再查找静态库

      • gcc -o hello main.c -lhello2 -lmyhello -Wl,-rpath,. -L.              动静都可以。
      • gcc -o hello main.c libhello2.a -lmyhello -Wl,-rpath,. -L.         则要求libhello2.a和 libmyhello.so或libmyhello.a
      • gcc -o hello main.c -lhello2 -lmyhello -Wl,-rpath,. -L. -static  则要求libhello2.a和libmyhello.a



      原创粉丝点击