动态库:
这类库的名字一般是libxxx.so.M.N,同样的xxx为库的名字,M是库的主版本号,N是库的副版本号。当然也可以不要版本号,但名字必须有。相对于静态函数库,动态函数库在编译的时候并没有被编译进目标代码中,你的程序执行到相关函数时才调用该函数库里的相应函数,因此动态函数库所产生的可执行文件比较小。由于函数库没有被整合进你的程序,而是程序运行时动态的申请并调用,所以程序的运行环境中必须提供相应的库。动态函数库的改变并不影响你的程序,所以动态函数库的升级比较方便。linux系统有几个重要的目录存放相应的函数库,如/lib /usr/lib。
动态库创建与链接分为两种:
1、直接编译链接
例子:
dymicfun.h dymicfun.cpp main.cpp
dymicfun.h
#ifndef __DYMICFUN_H_
#define __DYMICFUN_H_
#ifdef __cplusplus
extern "C"{
#endif
int max(int a,int b);
#ifdef __cplusplus
}
#endif
dymicfun.cpp
#include "dymicfun.h"
extern "C" int max(int a,int b)
{
return a > b ? a : b;
}
main.cpp
#include <stdio.h>
int main(int argc,char** argv)
{
printf("max is %d",max(1,2));
return 0;
}
编译动态库文件:
g++ -fPIC -c dymicfun.cpp dymicfun.o
g++ -shared -o libdymicfun.so dymicfun.o
链接动态库文件:
g++ main.cpp -o main -L. libdymicfun.so
查看进程依赖的库文件:
nm main
2、代码执行链接:动态链接
dymicfun.h dymicfun.cpp main.cpp
dymicfun.h
#ifndef __DYMICFUN_H_
#define __DYMICFUN_H_
#ifdef __cplusplus
extern "C"{
#endif
class A;
int max(int a,int b);
A* getA();
int deleteA(A *);
#ifdef __cplusplus
}
#endif
class A{
public:
A();
A(const A&);
virtual ~A();
int amax(int a,int b);
int getdata();
private:
int c;
};
#endif
dymicfun.cpp
#include "dymicfun.h"
#include <stdio.h>
#include <stdlib.h>
extern "C" int max(int a,int b)
{
return a > b ? a : b;
}
extern "C" A* getA()
{
return new A();
}
extern "C" int deleteA(A *opt)
{
if(NULL != opt){
delete opt;
opt = NULL;
}
}
A::A():c(0)
{
}
A::~A()
{
}
A::A(const A& opt):c(opt.c)
{
}
int A::amax(int a, int b)
{
c = a > b ? a : b;
return 0;
}
int A::getdata()
{
return c;
}
main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <gnu/lib-names.h>
#include "dymicfun.h"
typedef int (*funmax)(int a,int b);
typedef A* (*create_A)();
typedef int (*delete_A)(A *);
int main(int argc,char** argv)
{
void *handle = NULL;
char *error = NULL ;
handle = dlopen("./libdymicfun.so",RTLD_LAZY);
if(NULL == handle){
printf("%s\n",dlerror());
return 0;
}
funmax max_fun = (funmax)dlsym(handle,"max");
printf("max is %d\n",max_fun(1,2));
if(NULL == max_fun){
printf("%s\n",dlerror());
dlclose(handle);
return 0;
}
create_A create_fun = (create_A)dlsym(handle,"getA");
if(NULL ==create_fun){
printf("%s\n",dlerror());
dlclose(handle);
return 0;
}
delete_A delete_fun = (delete_A)dlsym(handle,"deleteA");
if(NULL == delete_fun){
printf("%s\n",dlerror());
dlclose(handle);
return 0;
}
A *class_A = create_fun();
if(NULL != class_A){
class_A->amax(3,4);
int d = class_A->getdata();
printf("d = %d",d);
delete_fun(class_A);
}
else{
printf("create_fun error\n");
}
dlclose(handle);
return 0;
}
编译方式
1、非调试版本:
g++ -fPIC -c dymicfun.cpp -o dymicfun.o
g++ -shared -o libdymicfun.so dymicfun.o
g++ main.cpp dymicfun.o -o main -ld
2、调试版本:
g++ -fPIC -c dymicfun.cpp -o dymicfun.o
g++ -shared -o libdymicfun.so dymicfun.o
g++ -g main.cpp dymicfun.o -o main -ldl