如何在linux下写动态链接库并卖给别人?

 前面我们讨论了linux下的静态链接库, 现在是该说说linux下的动态链接库了。 在本文中, 我们不讲动态链接库有哪些好处, 你去网上搜, 一搜一大堆。 我们仅仅来说说, 如何在linux下写动态链接库, 如何卖掉。

卖方

步骤一:

写test.h文件:

void print();

写test.c文件:

#include <stdio.h>
#include "test.h"
void print()
{
    printf("I am a little bit hungry now.\n");
}

步骤二:      

制作动态链接库, 如下:

[taoge@localhost learn_c]$ ls
test.c  test.h
[taoge@localhost learn_c]$ gcc -c test.c
[taoge@localhost learn_c]$ ls
test.c  test.h  test.o
[taoge@localhost learn_c]$ gcc -shared -fPCI -o libtest.so test.o
[taoge@localhost learn_c]$ ls
libtest.so  test.c  test.h  test.o
[taoge@localhost learn_c]$ file libtest.so 
libtest.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (GNU/Linux), dynamically linked, not stripped
[taoge@localhost learn_c]$ 

步骤三: 

以1块钱的价格,把libtest.so和test.h卖给别人。

买方

步骤一:

写应用程序main.c, 如下:

#include<stdio.h>
 
int main()
{
    print();
    return 0;
}

步骤二:

花1块钱, 从卖方那里买来libtest.so和test.h, 并使用它们, 如下(要注意, 如下编译命令, 并没有把libtest.so编译到a.out中, 理论上也没有。实际上也可以用strings命令验证一下, 确实没有):

[taoge@localhost learn_c]$ ls
libtest.so  main.c  test.h
[taoge@localhost learn_c]$ gcc main.c -L. -ltest
[taoge@localhost learn_c]$ ./a.out 
./a.out: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
[taoge@localhost learn_c]$ cp libtest.so /usr/lib
cp: cannot create regular file `/usr/libtest.so': Permission denied
[taoge@localhost learn_c]$ su root
Password: 
[root@localhost learn_c]# cp libtest.so /usr/lib   //这个路径是默认的动态库搜索路径
[root@localhost learn_c]# ./a.out 
I am a little bit hungry now.
[root@localhost learn_c]# exit
exit
[taoge@localhost learn_c]$ ./a.out 
I am a little bit hungry now.
[taoge@localhost learn_c]$ ls
a.out  libtest.so  main.c  test.h
[taoge@localhost learn_c]$ rm libtest.so test.h main.c
[taoge@localhost learn_c]$ ls
a.out
[taoge@localhost learn_c]$ ./a.out 
I am a little bit hungry now.
[taoge@localhost learn_c]$ 

可见, 要把动态链接库放到/usr/lib下, 才能被加载, 而要在这个目录下添加文件, 必须有root权限。 其余的, 不说自明吧。

OK,  linux下的动态链接库先说到这里, 后面还会继续侃, 先睡觉。
--------------------- 
作者:stpeace 
原文:https://blog.csdn.net/stpeace/article/details/47047679 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值