Linux系统共享库编程

发表于:2013-3-28 10:30

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:苏怀广    来源:51Testing软件测试网采编

  一、说明

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

  二、创建共享库

  在mytestso.c文件中,代码如下:

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

int GetMax(int a, int b)
{
 if (a >= b)
  return a;
 
 return b;
}

int GetInt(char* psztxt)
{
 if (0 == psztxt)
  return -1;
 
 return atoi(psztxt);

  然后使用下列命令进行编译:

gcc -fpic -shared mytestso.c -o mytestso.so

  -fpic 使输出的对象模块是按照可重定位地址方式生成的

  编译成功后,当前目录下有mytestso.so,此时已成功创建共享库mytestso.so。

  三、使用共享库

  共享库中的函数可被主程序加载并执行,但是不必编译时链接到主程序的目标文件中。主程序使用共享库中的函数时,需要事先知道所包含的函数的名称(字符串),然后根据其名称获得该函数的起始地址(函数指针),然后即可使用该函数指针使用该函数。

  在mytest.c文件中,代码如下:

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

int main(int argc, char* argv[])
{
 void* pdlhandle;
 char* pszerror;
 
 int (*GetMax)(int a, int b);
 int (*GetInt)(char* psztxt);
 
 int a, b;
 char* psztxt = "1024";
 
 // open mytestso.so
 pdlhandle = dlopen("./mytestso.so", RTLD_LAZY);
 pszerror = dlerror();
 if (0 != pszerror) {
  printf("%s\n", pszerror);
  exit(1);
 }
 
 // get GetMax func
 GetMax = dlsym(pdlhandle, "GetMax");
 pszerror = dlerror();
 if (0 != pszerror) {
  printf("%s\n", pszerror);
  exit(1);
 }
 
 // get GetInt func
 GetInt = dlsym(pdlhandle, "GetInt");
 pszerror = dlerror();
 if (0 != pszerror) {
  printf("%s\n", pszerror);
  exit(1);
 }
 
 // call fun
 a = 200;
 b = 600;
 printf("max=%d\n", GetMax(a, b));
 printf("txt=%d\n", GetInt(psztxt));
 
 // close mytestso.so
 dlclose(pdlhandle);
}
     

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号