编译小结(4) 说说静态库(.a)

来源:互联网 发布:mssql数据库日志截断 编辑:程序博客网 时间:2024/05/16 17:42
  静态库的概念和特点就不说了,这里只展示下编译过程和调用时会出现的问题。

/*例子目录结构:[root@ol64 test4]# ls *main.clib:add.c  calc.h  sub.c操作系统: Oracle Linux 6.4编译版本:[root@ol64 test4]# gcc --versiongcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)*/

程序代码附在 编译小结(3) 动态库(.so)编译及二种调用技巧 一章的后面。

编译静态库:


直接用命令行搞定:
[root@ol64 lib]# gcc -c add.c[root@ol64 lib]# gcc -c sub.c[root@ol64 lib]# ls add.c  add.o  calc.h  sub.c  sub.o[root@ol64 lib]# ar -rcs libcalc.a add.o sub.o[root@ol64 lib]# ar -t libcalc.aadd.osub.o[root@ol64 lib]# 

一步一步看我的演示过程:
//首先直接编译会说找不到静态库中的"sub" 和"ad"函数[root@ol64 test4]# gcc -m64 -I./lib   -o demo main.c/tmp/ccHsyaIp.o: In function `main':main.c:(.text+0x14): undefined reference to `sub'main.c:(.text+0x25): undefined reference to `add'collect2: ld returned 1 exit status//把静态库路径放到 静态库查找环境变量"LIBRARY_PATH"中去。[root@ol64 test4]# export LIBRARY_PATH=`pwd`/lib//很奇怪的,会仍报错。 虽然环境变量, "-L"参数我都设了[root@ol64 test4]#   gcc -m64 -I./lib  -L./lib -lcalc -o demo main.c/tmp/ccrnYQX7.o: In function `main':main.c:(.text+0x14): undefined reference to `sub'main.c:(.text+0x25): undefined reference to `add'collect2: ld returned 1 exit status//尝试调整一下顺序,可以了。[root@ol64 test4]#  gcc -o demo main.c -m64 -I./lib  -L./lib -lcalc [root@ol64 test4]# ./demoadd() = 8 sub() = 2MAIL:xcl_168@aliyun.com BLOG:http://blog.csdn.net/xcl168[root@ol64 test4]# //尝试把 "-L"参数去掉。因为我已在环境变量"LIBRARY_PATH"中指定过了。[root@ol64 test4]# gcc -o demo2 main.c -m64 -I./lib -lcalc[root@ol64 test4]# ./demo2add() = 8 sub() = 2MAIL:xcl_168@aliyun.com BLOG:http://blog.csdn.net/xcl168[root@ol64 test4]# echo $LIBRARY_PATH/xcl/test4/lib//再把顺序换一下,结果报错了。[root@ol64 test4]# gcc -m64 -I./lib -lcalc  -o demo2 main.c/tmp/ccshK94c.o: In function `main':main.c:(.text+0x14): undefined reference to `sub'main.c:(.text+0x25): undefined reference to `add'collect2: ld returned 1 exit status

 综上。 静态库编译时,参数顺序很重要。我上面只是调整了下顺序编译就通不过了。
 而动态库没这种问题。

 另要注意在默认情况下,gcc在链接时优先使用动态链接库,只有当动态链接库不存在时才考虑使用静态链接库。

附录:

静态库链接时搜索路径顺序:
1. ld会去找GCC命令中的参数-L
2. 再找gcc的环境变量LIBRARY_PATH
3. 再找内定目录 /lib /usr/lib /usr/local/lib 这是当初compile gcc时写在程序内的

有关环境变量:
LIBRARY_PATH环境变量:指定程序静态链接库文件搜索路径

LD_LIBRARY_PATH环境变量:指定程序动态链接库文件搜索路径


MAIL: xcl_168@aliyun.com
BLOG:http://blog.csdn.net/xcl168


原创粉丝点击