《Advanced Linux Programming》读书笔记(1)
动态加载共享库,这个知识点书上简单提了下,我做了个简单例子加深印象
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下,
作者:洞庭散人
出处:http://phinecos.cnblogs.com/
本博客遵从Creative Commons Attribution 3.0 License,若用于非商业目的,您可以自由转载,但请保留原作者信息和文章链接URL。
posted on 2009-03-23 17:30 Phinecos(洞庭散人) 阅读(1080) 评论(0) 编辑 收藏 举报