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

来源:互联网 发布:cpu硅脂品牌 知乎 编辑:程序博客网 时间:2024/05/24 04:52

        前面我们讨论了如何玩Windows下的静态链接库、动态链接库, 也说了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]$ lstest.c  test.h[taoge@localhost learn_c]$ gcc -c test.c[taoge@localhost learn_c]$ lstest.c  test.h  test.o[taoge@localhost learn_c]$ gcc -shared -fPCI -o libtest.so test.o[taoge@localhost learn_c]$ lslibtest.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 "test.h"int main(){print();return 0;}

       步骤二:

       花1块钱, 从卖方那里买来libtest.so和test.h, 并使用它们, 如下:

[taoge@localhost learn_c]$ lslibtest.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/libcp: cannot create regular file `/usr/libtest.so': Permission denied[taoge@localhost learn_c]$ su rootPassword: [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]# exitexit[taoge@localhost learn_c]$ ./a.out I am a little bit hungry now.[taoge@localhost learn_c]$ lsa.out  libtest.so  main.c  test.h[taoge@localhost learn_c]$ rm libtest.so test.h main.c[taoge@localhost learn_c]$ lsa.out[taoge@localhost learn_c]$ ./a.out I am a little bit hungry now.[taoge@localhost learn_c]$ 
       可见, 要把动态链接库放到/usr/lib下, 才能被加载, 而要在这个目录下添加文件, 必须有root权限。 其余的, 不说自明吧。


       OK,  linux下的动态链接库先说到这里, 后面还会继续侃, 先睡觉。








 

        

0 0