星零
No reason. I just like it.

  最近在专研Linux,看书看到GCC的使用时手痒写了一下C的动态库试试,我写了一个简单的string的结构体和连接方法打包成动态库。下面是代码:

 str.h

 1 #ifndef STR_H
 2 #define STR_H
 3 typedef struct{
 4     char* chs;
 5     int length;
 6 }* strp,str;
 7 
 8 str concat(str,str);
 9 #endif
10 

 

strfun.c

 1 #include "str.h"
 2 #include <stdlib.h>
 3 
 4 str concat(str s1,str s2)
 5 {
 6     int len = s1.length+s2.length+1;
 7     char* s3 = (char*)malloc(len);
 8     int i;
 9     for(i=0;i<len-1;i++)
10     {
11         if(i<s1.length)
12         {
13             *(s3+i) = *(s1.chs+i);
14         }
15         else
16         {
17             *(s3+i) = *(s2.chs+i-s1.length);
18         }
19     }
20 
21     str res;
22     res.length = len;
23     res.chs = s3;
24     return res;
25 }
26 

 

main.c

 1 #include <stdio.h>
 2 #include "str.h"
 3 
 4 int main(int strc,char* strs[])
 5 {
 6     str s1,s2,s3;
 7     s1.chs = "Hello ";
 8     s1.length = 6;
 9     s2.chs = "World!";
10     s2.length = 6;
11     
12     s3 = concat(s1,s2);
13     printf(s3.chs);
14     
15     return 0;
16 }
17 
18 

 代码完成了开始编译,首先是把strfun.c 编译成object file(对象文件):

gcc -Wall -I./ -c strfun.c

 接下来是把object file打包成一个share object(共享库)也就是Windows下的dll(动态链接库):

gcc -shared -o libstrf.so strfun.o

#Cygwin中用下面命令

gcc 
-shared -o libstrf.dll strfun.o

 最后是编译main.c生产可执行文件

gcc -Wall -I./ -L./ -lstrf -o run main.c

 大功告成,试一下吧。如果在Linux中则需要把*.so文件放到/usr/lib 中,cygwin的话把*.dll文件放在当前目录(.exe所在的目录)就可以了。

运行./run

Hello World!

 可以正常运行了,但程序真的在调用动态链接库吗?把*.so(*.dll)文件删了再试试./run什么也没有了,这证明编译出来的程序确实是在调用动态链接库执行的。

 

posted on 2009-02-07 00:39  Star.Stroll  阅读(6197)  评论(0编辑  收藏  举报