动态加载共享库,这个知识点书上简单提了下,我做了个简单例子加深印象
main.c
#include
<
stdio.h
>
#include < dlfcn.h >
int main( int argc, char ** argv)
{
void * handle = dlopen ( " libreciprocal .so " , RTLD_LAZY);
double ( * reciprocal)( int ) = dlsym (handle, " reciprocal " );
int num;
num = atoi(argv[ 1 ]);
printf(“ % d 的倒数是 % g\n”,num, reciprocal(num));
dlclose (handle);
return 0 ;
}
#include < dlfcn.h >
int main( int argc, char ** argv)
{
void * handle = dlopen ( " libreciprocal .so " , RTLD_LAZY);
double ( * reciprocal)( int ) = dlsym (handle, " reciprocal " );
int num;
num = atoi(argv[ 1 ]);
printf(“ % d 的倒数是 % g\n”,num, reciprocal(num));
dlclose (handle);
return 0 ;
}
reciprocal.hpp
#ifdef __cplusplus
extern " C " {
#endif
extern double reciprocal ( int i);
#ifdef __cplusplus
}
#endif
extern " C " {
#endif
extern double reciprocal ( int i);
#ifdef __cplusplus
}
#endif
reciprocal.cpp
#include
<
cassert
>
#include " reciprocal.hpp "
double reciprocal ( int i) {
// I should be non-zero.
assert (i != 0 );
return 1.0 / i;
}
#include " reciprocal.hpp "
double reciprocal ( int i) {
// I should be non-zero.
assert (i != 0 );
return 1.0 / i;
}
具体编译过程:
注:这里我将共享库放置在/home/phinecos/lib下,