看风听雨之自学编程之动态库

本文介绍了一种在Linux环境下使用动态库的方法,并提供了详细的代码示例。通过将库文件与测试程序放置在同一目录并采用动态定位的方式加载,解决了库文件不在默认路径或未注册环境变量时遇到的问题。

动态库编程

Linux中so文件为共享库;windows下dll文件为共享库; 

在linux中动态库的调用函数是 dlopen();            在Windows中动态库的调用是LoadLibrary();

Linux:

库文件 fun.c

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


int add(int a, int b)    //加法
{
return a+b;
}
int sub(int a, int b)   //减法
{
return a-b;
}
int mul(int a, int b)   //乘法
{
return a*b;
}
int div(int a, int b)   //除法
{
return a/b;
} 


gcc -c  so.c  /  
  gcc fun.c -fPIC -shared -o libtest.so //文件生成动态链接库文件libtest.so



test.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>
#include <string.h>


typedef  int(* fun_prt)(int ,int);
int main()
{
    
    
    char file_url[80];
    char file_name[30];
    void *lib_prt;
    fun_prt fun_prt= NULL;
    int  a=3;
    int  b=4;
    
    getcwd(file_url, sizeof(file_url));
    
    strcpy(file_name ,"/libtest.so");    
    strcat(file_url , file_name);        //拼字符串
    //printf("current working directory: %s\n", file_url);
    lib_prt=dlopen(file_url, RTLD_LAZY);
    if(! lib_prt)
    {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
     }
     
     //清除之前存在的错误
   dlerror();
    
    fun_prt=dlsym(lib_prt , "add");
    
    if(!fun_prt)
    {
         fprintf(stderr, "%s\n", dlerror());
         exit(EXIT_FAILURE);
    }
    printf("add: %d\n", (*fun_prt)(a,b));
    
    
    
    
    return 0;
    




}


gcc  -o test test.c -ldl  //生成测试程序


总结 看了很多教程,在so文件不放在默认的bin文件夹,或不注册环境变量的情况下。

        总是编译失败,或者运行失败。

后来修改为动态定位相同目录下指定文件夹的方式,拼接文件名,然后直接传指针才获得正确结果! 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值