惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
Engineering at Meta
Engineering at Meta
美团技术团队
N
Netflix TechBlog - Medium
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
F
Fortinet All Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Last Week in AI
Last Week in AI
The Cloudflare Blog
量子位
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
腾讯CDC
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
DataBreaches.Net
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - Star.Stroll

【Chrome扩展】Reload image 重载图片 [原创]RegularJS [原创]虚拟化技术真的能让企业降低成本吗? [原创]纯Java获得本地MAC地址 [原创]Cygwin的中文支持(解决乱码) [原创]程序员日志:自制随笔程序 [原创]程序员日志:程序员的快捷方式 [原创]Java Socket(套接字)自学笔记1 [原创]透明的DIV提示框(兼容IE与Firefox) 深入HashCode方法 JavaScript代码实例:拖动对象 Drag Object (兼容:IE、Firefox、Opera ... ) Tomcat中用web.xml控制Web应用详解(2) Tomcat中用web.xml控制Web应用详解(1) java.sql.ResultSet 新增、更新、刪除資料 [原创]一个简单例子解释 Java 工厂模式 [原创]Object.clone()的作用与用法 Java 范型编程 Singleton模式(单态模式) Builder模式
[原创]GCC动态链接库的编译与使用简例
Star.Stroll · 2009-02-07 · via 博客园 - Star.Stroll

  最近在专研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什么也没有了,这证明编译出来的程序确实是在调用动态链接库执行的。