Linux系统共享库编程

1、

类似Windows系统中的动态链接库,Linux中也有相应的共享库用以支持代码的复用。Windows中为*.dll,而Linux中为*.so。下 面详细介绍如何创建、使用Linux的共享库。

2、创建共享库

//sayhello.c

#include<stdio.h>

int sayhello( void )
{
    printf("hello form sayhello function!/n");
    return 0;
}

void saysomething(char * str)
{
    printf("%s/n",str);
}
用下面的命令可以生成共享库

gcc -fpic -shared sayhello.c -o libsay.so

 解释:-f 后面跟一些编译选项,PIC 是 其中一种,表示生成位置无关代码(Position Independent Code)。

 

3、使用共享库

//say.c

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

int main(int argc,char *argv[])
{
    void *handle;
    char *error;
    void (*sayhello)(void);
    void (*saysomething)(char *);

    handle = dlopen("./libsay.so",RTLD_LAZY);
    if(error = dlerror()) {
        printf("%s/n",error);
        exit(1);
        }

    sayhello = dlsym(handle,"sayhello");
    if(error = dlerror()) {
        printf("%s/n",error);
        exit(1);
    }

    saysomething = dlsym(handle,"saysomething");
    if(error = dlerror()) {
        printf("%s/n",error);
        exit(1);
    }

    sayhello();
    saysomething("This is something");

    dlclose(handle);
   
    return 0;
}

解释:LINUX下要使用动态链接库,源程序就需要包含dlfcn.h头文件,该头文件定义了调用动态链接库的函数的原型,例如dlopen等。

编译上述源文件使用的命令为:gcc say.c -ldl -o say 其中选项-ldl表示生成的模块需要引用共享库。若未加该选项将会出现“undefined reference to dlopen”等这样的错误

http://blog.chinaunix.net/u3/99873/showart_2064337.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值