日期:2014-05-16  浏览次数:20669 次

LINUX下动态库的使用方式

包括三个部分:

 1. 动态库编译

 2. 动态库使用方式:编译链接

 3. 动态库使用方式: dlopen

今天面试有人说你连基本的动态库加载都不清楚?!错要承认挨打站稳;

如下:

---------文件列表-----------

hello.c  ---- hello()函数 输出字符串

hello.h  --- 包含一个头文件

main.c  ---编译方式使用动态库的文件

dlmain.c ---dlopen方式使用动态库的文件


----hello.h---

#ifndef _HELLO_H_
#define _HELLO_H_
void hello(const char* name);
#endif


----hello.c---

#include "hello.h"
int main()
{
 hello("everyone");
 return 0;
}

---mian.c---

#include "hello.h"
int main()
{
 hello("everyone");
 return 0;
}


---dlmain.c---

#include<stdio.h>
#include<stdlib.h>
#include<dlfcn.h>
int main()
{
   void *handle = NULL;
   void (*hello)(const char* str);
   handle = dlopen("./libmyhello.so", RTLD_LAZY);
   if(handle==NULL)
   {
       printf("dll loading error.\n");
       return 0;
   }    
   hello = (void(*)(const char*))dlsym(handle,"hello");
   if(dlerror()!=NULL)
   {
     printf("fun load error.\n");
     return 0;
   }

  
   hello("dlopen ");   

   dlclose(handle ); 
}


实验:如果先dlclose 再调用so库中查找到的函数,会发生什么事儿?

PS:-> 符号表示输出,不是命令。

----------前序,静态库的方式-----------

1.//先生成 中间 .o文件 

#gcc hello.c ->hell.o

2. //打包静态库 ar功能请再查询

#ar cr libmyhello.a hello.o-> libmyhello.a

3. // 使用静态库生成目标文件

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

4.//执行

 #./hello  -> hello everyone! 

5.//删除静态库,再执行还是正确,说明hello目标文件中已经包含了 libmyhello.o内容;  

#rm libmyhello.o

#./hello   -> hello everyone! 


---------动态库使用,编译链接方式------------

1.生成so文件

#gcc -shared -fPCI -o libmyhello.so hello.o   ->libmyhello.so

2. 编译目标文件

gcc -o hello main.c -L . -lmyhello  ->hello
3.执行目标文件     

#./hello   会报错:while loading shared libraries:libmyhello.so:can not open  shared object:No shuch file or directory
4. 拷贝so到用户库

#cp libmyhello.so /usr/lib           拷贝自己的so库到 /usr/lib 下,也可以用修改环境变量等方式,请自行扩展

#./hello  -> hello everyone!          这次正确了



---------动态库使用