用c语言调用动态库

604 篇文章 8 订阅
579 篇文章 5 订阅
动态加载是在 程序运行时用dlopen,dlsym函数进行的。
静态加载发生在 程序装载时
1.1 用c语言 静态方式调用动态库libsthc.so
/*
 * ctest.c
 * Testing program for libsthc.so library  //测试程序为在c语言中调用libsthc.so库
 * in c languange
 *
*/
#include "libsthc.h"     //程序中需包含头文件,程序会自动在 缺省的库(/usr/lib)里寻找libsthc.so,需在makefile具体指明库名;或者放在当前文件夹;如果都不在需指明路径
{
         printf("%d\n", add(1, 2));
         return 0;
}
 
#makefile:
ctest:ctest.o
         gcc ctest.o -lsthc -o ctest    //-lsthc就是库名
ctest.o:ctest.c
         gcc -c ctest.c -o ctest.o
all:ctest
clean:
         rm -f *.o ctest
 
 
1.2 用c语言动态方式调用动态库libsthc.so:
/*cdltest.c*/
#include "stdio.h"
#include "stdlib.h"
#include "dlfcn.h"    //需要此头文件
 
int main(void)
{
         void *handle;
         int (*fcn)(int x, int y);
         const char *errmsg;
        
         /* open the library */   //打开库
         handle = dlopen("libsthc.so", RTLD_NOW);
         if(handle == NULL)
         {
                   fprintf(stderr, "Failed to load libsthc.so: %s\n", dlerror());
                   return 1;
         }
         dlerror();
 
         //*(void **)(&fcn) = dlsym(handle, "add");            //ok
         fcn = dlsym(handle, "add");                                   //ok
         if((errmsg = dlerror()) != NULL)
         {
                   printf("%s\n", errmsg);
                  return 1;
         }
         printf("%d\n", fcn(1, 5));
        
         dlclose(handle);
         return 0;
}
 
#makefile:
cdltest:cdltest.o
         gcc cdltest.o -ldl -lsthc -o cdltest   //多写了-ldl,即多需要这个库
cdltest.o:cdltest.c
         gcc -c cdltest.c -o cdltest.o
all:cdltest
clean:
         rm -f *.o cdltest
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值