Linux动态共享库与版本控制初记

记录一下,这东西以前一直都不理解,今天按照最简单的方式创建了一下,记录在此。

首先创建四个目录

src:用于放置源文件
lib:用于放置动态库文件
include:用于放置头文件
bin:用于放置最后的可执行文件

现在include目录下创建mytestso.h文件

#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 -Wl,-soname,-libhello.so.0 -o libhello.so.0.0.1
随后可以看到在这个目录下产生了一个名叫libhello.so.0.0.1的库文件,利用命令

mv libhello.so.0.0.0 ../lib
将这个库文件移动到lib目录下。并在lib目录下执行

ln -s libhello.so.0.0.1 libhello.so.0
以便创建一个软链接libhello.so.0.

至此,一个动态库文件已经全部搞好了,接下来就是如何调用它了。

切换到src目录下。创建文件mytest.c

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

int main(int argc, char* argv[])
{
   void* pdlhandle;
   char* pszerror;

   int (*GetMax)(int a, int b);
   int (*GetInt)(char* psztxt);
   void (*PrintVersion)(void);
   int a, b;
   char* psztxt = "1024";

   // open mytestso.so
   pdlhandle = dlopen("../lib/libhello.so.0", RTLD_LAZY);
   pszerror = dlerror();
   if (0 != pszerror) {
      printf("%s\n", pszerror);
      exit(1);
   }
#if 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));
#endif

   // close mytestso.so
   dlclose(pdlhandle);
}
保存,执行命令:

gcc mytest.c -o ../bin/mytest -ldl
在bin目录下会生成一个mytest的可执行文件,进入到bin目录,执行:

./mytest
获得结果:

max=600
txt=1024
到了这一步,动态库的创建,动态加载过程已经都完毕了。

对动态库命名的规则,gcc参数的意义下篇文章再说吧。


参考文章:http://www.vckbase.com/index.php/wv/1209






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值