博客首页 注册 建议与交流 排行榜 加入友情链接         宝宝相册的专门空间
推荐 投诉 搜索: 帮助

人参娃娃的技术博客

碧云天,黄花地,西风紧,北雁南飞。晓来谁染霜林醉?
  ivykiki.cublog.cn

关于作者
姓名:人参娃娃
职业:IT
年龄:25
位置:湖北武汉
个性介绍:探索~~~~
|| << >> ||
我的分类


load library
 

#include <stdio.h>
#include <dlfcn.h>

#define null 0

///* declarations used for dynamic linking support routines */

//extern void *dlopen (const char *, int);

//extern void *dlsym (void *, const char *);

//extern int dlclose (void *);

//extern char *dlerror (void);


int main(int argc, char **argv)
{
    printf("load so demo... \n");

    // open the library

    printf("opening libhello.so.1.0...\n");
    void* handler = dlopen("libhello.so.1.0", RTLD_LAZY);
    if(!handler) {
        printf("cannot open library: %s \n", dlerror());
        return 1;
    }
    
    // load the symbol

    printf("loading the symbol 'debug_print'...\n");
    typedef void (*symbol_t)();
    
    // reset dlerror

    symbol_t debug_print = null;
    debug_print = (symbol_t) dlsym(handler, "debug_print");
    if(!debug_print) {
        printf("cannot load the symbol 'debug_print': %s \n", dlerror());
        dlclose(handler);
        return 1;
    }
    
    // using the symbol

    printf("using the symbol 'debug_print'...\n");
    debug_print();
    
    // close the library

    printf("close the library...\n");
    dlclose(handler);
    return 0;

}

 

$gcc -c hello.c -o hello.o

1.连接成静态库
连接成静态库使用ar命令,其实ar是archive的意思
$ar cqs libhello.a hello.o
2.连接成动态库
生成动态库用gcc来完成,由于可能存在多个版本,因此通常指定版本号:
$gcc -shared -Wl,-soname,libhello.so.1 -o libhello.so.1.0 hello.o

另外再建立两个符号连接:
$ln -s libhello.so.1.0 libhello.so.1
$ln -s libhello.so.1 libhello.so
这样一个libhello的动态连接库就生成了。最重要的是传gcc -shared 参数使其生成是动态库而不是普通执行程序.
-Wl 表示后面的参数也就是-soname,libhello.so.1直接传给连接器ld进行处理。实际上,每一个库都有一个soname,当连接器发现它正在查找的程序库中有这样一个名称,连接器便会将soname嵌入连结中的二进制文件内,而不是它正在运行的实际文件名,在程序执行期间,程序会查找拥有soname名字的文件,而不是库的文件名,换句话说,soname是库的区分标志。
这样做的目的主要是允许系统中多个版本的库文件共存,习惯上在命名库文件的时候通常与soname相同
libxxxx.so.major.minor
其中,xxxx是库的名字,major是主版本号,minor 是次版本号

至于头文件的使用 只要.c文件和.h文件在同一目录下就可以直接用#include "your.h" 如果在.c文件的上层目录 那只要做如下修改#include "../your.h" 就能够让你的编译器找到了!

发表于: 2008-05-16,修改于: 2008-05-16 16:15,已浏览64次,有评论0条 推荐 投诉


网友评论
 发表评论