Linux中如何创建静态库和动态库
2013-01-29 19:01
274 查看
在windows下动态链接库是以.dll后缀的文件,二在Linux中,是以.so作后缀的文件。 动态链接库的好处就是节省内存空间。 1、Linux下创建动态链接库 在使用GCC编译程序时,只需加上-shared选项即可,这样生成的执行程序即为动态链接库。 例如有文件:hello.c x.h main.c 编译:gcc hello.c -fPIC -o libhello.so 其中-fPIC选项的作用是:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的, 所以动态载入时是通过代码拷贝的方式来满足不同的调用,而不能达到真正的代码段共享的目的. 将main.c与hello.so动态库gcc main.c -L. -lhello -o main 一、动态链接库 1.创建hello.so动态库 #include <stdio.h> void hello(){ printf("hello world\n"); } 复制代码 编译:gcc -fPIC -shared hello.c -o libhello.so 2.hello.h头文件 void hello(); 3.链接动态库 #include <stdio.h> #include "hello.h" int main(){ printf("call hello()"); hello(); } 复制代码 编译: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/这样,再次执行就成功输入: call hello() 二、静态库 文件有:main.c、hello.c、hello.h 1.编译静态库hello.o: gcc hello.c -o hello.o #这里没有使用-shared 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 输出:call hello() 三、借助自带的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” |
相关文章推荐
- Linux中如何创建静态库和动态库
- Linux中如何创建静态库和动态库
- Linux中如何创建静态库和动态库
- Linux中如何创建静态库和动态库
- Linux中如何创建静态库和动态库
- Linux中如何创建静态库和动态库
- 在Linux中创建静态库和动态库
- 问题集合 ---- linux 静态库和动态库创建、检查、使用建议
- Linux中创建静态库和动态库
- Linux下静态库_库的基本概念;如何生成静态库动态库;nm查看库中包含那些函数、ar生成静态库,查看库中包含那些.o文件、ldd查看程序依赖的.so文件;gcc/g++与库相关的参数-L,-l,-f
- Linux下静态库_库的基本概念;如何生成静态库动态库;nm查看库中包含那些函数、ar生成静态库,查看库中包含那些.o文件、ldd查看程序依赖的.so文件;gcc/g++与库相关的参数-L,-l,-f
- Linux下静态库_库的基本概念;如何生成静态库动态库;nm查看库中包含那些函数、ar生成静态库,查看库中包含那些.o文件、ldd查看程序依赖的.so文件;gcc/g++与库相关的参数-L,-l,-f
- linux下的静态库创建与查看,及如何查看某个可执行依赖于哪些动态库
- 在Linux下如何使用GCC编译程序、简单生成静态库及动态库
- VisualGDB系列7:使用VS创建Linux静态库和动态库
- 在Linux中创建静态库和动态库
- Linux创建动态库和静态库
- 在Linux中创建静态库和动态库
- Linux下静态库,动态库的创建和使用,多个动态库使用
- 在Linux中创建静态库和动态库