一.生成动态库
calculate.c文件
intadd(inta,int b ) { return a b; (int b ) int b,int b ) ) { return a-b; }intmul(inta,int b ) { return a*b; }floatdiv(inta,int b ) ) { return a/b; }编译并生成动态库
gcc-fpic-shared caculate.c-olibcaculate.so
二.直接链接动态库
# include stdio.h # include stdlib.h # include string.hvoidmain (void ) )2=%d(n ),add )2); printf(10-2=%d(n ),sub ) 10,2 ); }使用步骤如下。
1、export LD_LIBRARY_PATH=.
errorwhileloadingsharedlibraries 3360 lib *.so : cannotopensharedobjectfile 3360 nosuchfileordirectory出来
2、gcc test _ dlopen.c-l.- lcaculate-o test _ dlopen
3、执行./test_dlopen
三.使用dlopen函数加载
相关说明:
# include dlfcn.h void * dlopen (const char * filename,int flags ); flags:RTLD_LAZY保留决定,根据需要解开符号RTLD_NOW并立即决定,在返回之前解除所有未确定的符号。 intdlclose(void*Handle ); Char*Dlerror(void; void*dlsym(void*Handle,const char *symbol ); 例如:
# include stdio.h # include stdlib.h # include string.h # include dlfcn.htype defint (* cal ) ) int,int ); voidmain(void ) { void *handle; handle=dlopen ('./lib calculate.so ',RTLD_LAZY ); if(handle==null ) fprintf(stderr,' %sn ',dlerror ) ); 返回; }caladd=dlsym(Handle,' add '; printf(%d(n ),add ) 1,2 ); calsub=dlsym(Handle,' sub ' ); printf(%d(n ),sub ) 10,2 ); dclose(handle ); }执行命令:
GCT est _ dlopen2. c-LDL-o test _ dlopen 2
./test_dlopen2