Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176490
  • 博文数量: 32
  • 博客积分: 499
  • 博客等级: 下士
  • 技术积分: 347
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-22 14:47
文章存档

2012年(10)

2011年(19)

2010年(3)

分类:

2012-01-08 22:34:33

原文地址:静态库与动态库 作者:zyd_cu

 

函数库分为静态库和动态库两种

 

静态库在程序编译时会被连接到目标代码中,程序运行时将不再需要该静态库。

动态库在程序编译时并不会被连接到目标代码中,而是在程序运行是才被载入,因此在程序运行时还需要动态库存在。

 

示例代码:

 

头文件  hello.h  

 

#ifndef _HELLO_H
#define _HELLO_H
void hello(void);
#endif

 

源文件  hello.c

 

void hello(void)
{
    printf("hello world\n");
}


 源文件  main.c

#include <stdio.h>

#include "hello.h"

int main()
{
    hello();
    return 0;
}

 

静态库的制作与使用

 

静态库实际上是o目标文件的一个归档,使用ar工具可以创建静态库。

#gcc –c hello.c

#ar cr libhello.a hello.o

 

使用静态库,运行时不依赖静态库

#gcc –o main main.c –L. –lhello  //生成可执行文件main

#./main   //hello world

#rm libhello.a –rf  //移除静态库

#./main   //hello world

 

动态库的制作与使用

   在制作动态库时,要制定-shared,并可通过-fPIC标志生成位置无关代码。

-shared
     Produce a shared object which can then be linked with othe objects to form an executable.  Not all systems support this
option.  For predictable results, you must also specify the same set of options that were used to generate code (`-fpic', `-fPIC', or model suboptions) when you specify this option.

 

# gcc -shared -fPIC -o libmyhello.so hello.o

# gcc -o hello main.c -L. -lmyhello

# ./hello

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

 

因为程序默认在/lib, /usr/lib, LD_LIBRARY_PATH, /etc/ld.so.conf指定的路径查找库,所以可以将libhello.so移动到/lib//usr/lib下,或将当前目录加入到环境变量LD_LIBRARY_PATH,或加到配置文件/etc/ld.so.conf(需要运行ldconfig)。

链接动态库的程序在运行时需要库的存在,因其在运行时动态加载库,从而缩小了可执行文件的体积,节省了磁盘空间,而且动态库可被多个用户程序共享,节省更多的内存空间。

 

 

 


阅读(686) | 评论(0) | 转发(0) |
0

上一篇:extern "C" 的用意

下一篇:int, long最大值

给主人留下些什么吧!~~