您的位置:首页 > 运维架构 > Linux

GCC生成及调用动态库和静态库

2018-03-28 21:14 344 查看
说明:本文全部使用的cpp文件,如果要编译C库请将g++替换为gcc
文件:reply.h,reply.cpp,test.cpp,主函数在test.cpp中
(一)静态库的生成及使用
1.生成.o目标文件
g++ -c reply.cpp
2.使用ar命令打包
ar crv libreply.a reply.o   #标注:reply为库名

3.编译test.cpp
 g++ -o test.out test.cpp -L.-lreply 


 g++ -o test.out test.cpp libreply.a

4.运行
./test.out
5.tips:对于ar命令的具体应用(查看静态库文件等),请查看ar命令的手册
man ar或ar
(二)动态库的生成及使用

1.生成.o目标文件
g++ -fPIC -c reply.cpp 
标注:-fPIC则表明使用地址无关代码。PIC:Position Independent Code.    
         如果不加需要像windows下dll文件一样,需要导出的函数加extern

2.打包为.so
g++ -shared -fPIC -o libreply.so reply.o  

3.编译test.cpp
 g++ -o test.out test.cpp -L. -lreply -Wl,--rpath=. 
标注:(1)这里的l是小写的L

          (2)-Wl,--rpath=. 是指定在程序运行时到哪个目录找.so链接库,此处设置为./,如果不设置,只会在系统库中查找libreply.so而导致在运行时报缺少库的错误,如下

./test.out: error while loading shared libraries: libreply.so: cannot open shared object file: No such file or directory

4.运行
./test.out

参考链接:https://blog.csdn.net/eastonwoo/article/details/8241693
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息