手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网站运营>建站经验>列表

Linux下的库(下)--重要的代码复用机制

来源:互联网 作者:west263.com 时间:2008-04-16
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

[leo@leo test]$ ldd a.out
linux-gate.so.1 => (0xffffe000)
libhello.so => not found
libc.so.6 => /lib/libc.so.6 (0x40034000)
/lib/ld-linux.so.2 (0x40000000)
果然如此,看到没有,libhello.so => not found。
linux为我们提供了两种解决方法:
1.能够把当前路径加入/etc/ld.so.conf中然后运行ldconfig,或以当前路径为参数运行ldconfig(要有root权限才行)。
2.把当前路径加入环境变量LD_LIBRARY_PATH中
当然,假如您觉得不会引起混乱的话,能够直接把该库拷入/lib,/usr/lib/等位置(无可避免,这样做也要有权限),这样链接器和加载器就都能够准确的找到该库了。
我们采用第二种方法:
[leo@leo test]$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
[leo@leo test]$ ldd a.out
linux-gate.so.1 => (0xffffe000)
libhello.so => ./libhello.so (0x4001f000)
libc.so.6 => /lib/libc.so.6 (0x40036000)
/lib/ld-linux.so.2 (0x40000000)
哈哈,这下ld-linux.so.2就能够找到libhello.so这个库了。
现在能够直接运行了:
[leo@leo test]$ ./a.out
Hello World


3.2 创建静态库
仍使用刚才的hello.c和test.c。
第一步,生成目标文档。
[leo@leo test]$ gcc -c hello.c
[leo@leo test]$ ls hello.o -l
-rw-r--r-- 1 leo users 840 5月 6 12:48 hello.o
第二步,把目标文档归档。
[leo@leo test]$ ar r libhello.a hello.o
ar: creating libhello.a
OK,libhello.a就是我们所创建的静态库了,简单吧:)
[leo@leo test]$ file libhello.a
libhello.a: current ar archive

下面一行命令就是教您如何在程式中链接静态库的:
[leo@leo test]$ gcc test.c -lhello -L. -static -o hello.static

我们来用file命令比较一下用动态库和静态库链接的程式的区别:
[leo@leo test]$ gcc test.c -lhello -L. -o hello.dynamic
正如前面所说,链接器默认会链接动态库(这里是libhello.so),所以只要把上个命令中的-static参数去掉就能够了。

用file实用程式验证一下是否按我们的需要生成了可执行文档:
[leo@leo test]$ file hello.static hello.dynamic
hello.static: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.6, statically linked, not stripped
hello.dynamic: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.6, dynamically linked (uses shared libs), not stripped
不妨顺便练习一下ldd的用法:
[leo@leo test]$ ldd hello.static hello.dynamic
hello.static:
not a dynamic executable
hello.dynamic:
linux-gate.so.1 => (0xffffe000)
libhello.so => ./libhello.so (0x4001f000)
libc.so.6 => /lib/libc.so.6 (0x40034000)
/lib/ld-linux.so.2 (0x40000000)

OK,看来没有问题,那就比较一下大小先:
[leo@leo test]$ ls -l hello.[ds]*
-rwxr-xr-x 1 leo users 5911 5月 6 12:54 hello.dynamic
-rwxr-xr-x 1 leo users 628182 5月 6 12:54 hello.static
看到区别了吧,链接静态库的目标程式和链接动态库的程式比起来简直就是个庞然大物!

这么小的程式,很难看出执行时间的差别,但是为了完整起见,还是看一下time的输出吧:
[leo@leo test]$ time ./hello.static
Hello World

real 0m0.001s
user 0m0.000s
sys 0m0.001s
[leo@leo test]$ time ./hello.dynamic
Hello World

real 0m0.001s
user 0m0.000s
sys 0m0.001s
假如程式比较大的话,应该效果会很明显的。


文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!