gcc 编译使用动态链接库和静态链接库

本文详细介绍了在Linux环境下如何创建动态链接库,包括编译过程、使用动态库的方法以及解决链接动态库时遇到的问题。同时,还对比了动态链接库与静态链接库的区别,展示了动态链接库的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在windows下动态链接库是以.dll后缀的文件,二在Linux中,是以.so作后缀的文件。
动态链接库的好处就是节省内存空间。
1、Linux下创建动态链接库
在使用GCC编译程序时,只需加上-shared选项即可,这样生成的执行程序即为动态链接库。

例如有文件:hello.c hello.h main.c

编译:gcchello.c-fPIC-olibhello.so
其中-fPIC选项的作用是:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的,
所以动态载入时是通过代码拷贝的方式来满足不同的调用,而不能达到真正的代码段共享的目的.
将main.c与hello.so动态库l链接

gccmain.c-L.-lhello-omain

一、动态链接库

1.创建hello.so动态库

hello.h

void hello();

hello.c

#include <stdio.h> void hello(){ printf("hello world\n"); } 编译:gcc -fPIC -shared hello.c -o libhello.so
main.c

#include"hello.h" int main() { hello(); return 0; } 编译:gcc main.c -L. -lhello -o main



 这里-L的选项是指定编译器在搜索动态库时搜索的路径,告诉编译器hello库的位置。"."意思是当前路径. 

3.编译成够后执行./main,会提示:

In function `main':main.c:(.text+0x1d): undefined reference to `hello'collect2: ld returned 1 exit status

这是因为在链接hello动态库时,编译器没有找到。解决方法:

sudo cp libhello.so /usr/lib/

可以使用ldd来查看动态链接情况:

ldd main

结果:
linux-gate.so.1 => (0x00efd000)
libhello.so => /usr/lib/libhello.so (0x00f6b000)
libc.so.6 => /lib/libc.so.6 (0x001a5000)
/lib/ld-linux.so.2 (0x00eb8000)
如果目标程序没有链接动态库,则打印“not a dynamic executable”

这样,再次执行就成功输出:hello world

二、静态库

文件有:main.c、hello.c、hello.h
1.编译静态库hello.o:

gcc hello.c -c  #这里没有使用-shared   
注意此处要用 -c选项,若不然,会出现
/usr/lib/gcc/i686-linux-gnu/4.6.1/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld 返回 1

 2.把目标文档归档
 

ar -r libhello.a hello.o #这里的ar相当于tar的作用,将多个目标打包。程序ar配合参数-r创建一个新库libhello.a,并将命令行中列出的文件打包入其中。这种方法,如果libhello.a已经存在,将会覆盖现在文件,否则将新创建。
3.链接静态库

gcc main.c -lhello -L. -static -o main 这里的-static选项是告诉编译器,hello是静态库。
或者:gcc main.c libhello.a -L. -o main 这样就可以不用加-static

4.执行./main

输出:hello world

参考:http://blog.youkuaiyun.com/a600423444/article/details/7206015

 
 
 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值