Linux操作系统下动态库的编写与调用.doc
上传人:qw****27 上传时间:2024-09-12 格式:DOC 页数:8 大小:71KB 金币:15 举报 版权申诉
预览加载中,请您耐心等待几秒...

Linux操作系统下动态库的编写与调用.doc

Linux操作系统下动态库的编写与调用.doc

预览

在线预览结束,喜欢就下载吧,查找使用更方便

15 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

1.用c语言写动态库:/**libsthc.h*Declarationsforfunctionadd*/#include"stdio.h"#include"stdlib.h"#include"stdarg.h"#ifdef__cplusplusextern"C"{#endifintadd(intx,inty);#ifdef__cplusplus}#endif/**libsthc.c*Implementationoffunctionadddeclaredinlibsthc.h*inclanguage*/#include"libsthc.h"intadd(intx,inty){returnx+y;}#makefilelibsthc.so:libsthc.ogcc-sharedlibsthc.o-lc-olibsthc.solibsthc.o:libsthc.clibsthc.hgcc-fPIC-clibsthc.c-olibsthc.oall:libsthc.soclean:rm-f*.o*.somake完成后,会生成一个动态库,即libsthc.so。为了使其他程序也可以使用该动态库,需要将库文件libsthc.so拷贝到/usr/lib目录下(由于权限的问题,一般要以root的身分进行拷贝),为了使其他程序也可以使用该动态库,需要将头文件libsthc.h拷贝到/usr/include目录下(由于权限的问题,一般要以root的身分进行拷贝)。1.1用c语言静态方式调用动态库libsthc.so:/**ctest.c*Testingprogramforlibsthc.solibrary*inclanguange*by玄机逸士*/#include"libsthc.h"intmain(void){printf("%d\n",add(1,2));return0;}#makefile:ctest:ctest.ogccctest.o-lsthc-octestctest.o:ctest.cgcc-cctest.c-octest.oall:ctestclean:rm-f*.octest1.2用c语言动态方式调用动态库libsthc.so:/*cdltest.c*/#include"stdio.h"#include"stdlib.h"#include"dlfcn.h"intmain(void){void*handle;int(*fcn)(intx,inty);constchar*errmsg;/*openthelibrary*/handle=dlopen("libsthc.so",RTLD_NOW);if(handle==NULL){fprintf(stderr,"Failedtoloadlibsthc.so:%s\n",dlerror());return1;}dlerror();//*(void**)(&fcn)=dlsym(handle,"add");//okfcn=dlsym(handle,"add");//okif((errmsg=dlerror())!=NULL){printf("%s\n",errmsg);return1;}printf("%d\n",fcn(1,5));dlclose(handle);return0;}#makefile:cdltest:cdltest.ogcccdltest.o-ldl-lsthc-ocdltestcdltest.o:cdltest.cgcc-ccdltest.c-ocdltest.oall:cdltestclean:rm-f*.ocdltest1.3用c++静态方式调用动态库libsthc.so:/*cpptest.cc*/#include"libsthc.h"usingnamespacestd;intmain(void){printf("%d\n",add(1,2));return0;}#makefile:cpptest:cpptest.og++cpptest.o–ocpptest-lsthccpptest.o:cpptest.ccg++-ccpptest.cc-Wno-deprecated-ocpptest.oall:cpptestclean:rm-f*.ocpptest1.4用c++动态方式调用动态库libsthc.so:/*cppdltest.cpp*/#include"stdio.h"#include"stdlib.h"#inc