gcc编译静态库和动态库
来源:互联网 发布:淘宝全国包邮图片 编辑:程序博客网 时间:2024/05/01 21:55
一、动态链接库
1.创建hello.so动态库
- #include <stdio.h>
- void hello(){
- printf("hello world\n");
- }
- 编译:gcc -fPIC -shared hello.c -o libhello.so
#include <stdio.h>void hello(){printf("hello world\n");}编译:gcc -fPIC -shared hello.c -o libhello.so
2.hello.h头文件
- void hello();
void hello();
3.链接动态库
- #include <stdio.h>
- #include "hello.h"
- int main(){
- printf("call hello()");
- hello();
- }
- 编译:gcc main.c -L. -lhello -o main
#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
In function `main': main.c:(.text+0x1d): undefined reference to `hello'collect2: ld returned 1 exit status这是因为在链接hello动态库时,编译器没有找到。
解决方法:
- sudo cp libhello.so /usr/lib/
sudo cp libhello.so /usr/lib/这样,再次执行就成功输入:
call hello()
二、静态库
文件有:main.c、hello.c、hello.h
1.编译静态库hello.o:
- gcc hello.c -o hello.o #这里没有使用-shared
gcc hello.c -o hello.o #这里没有使用-shared
2.把目标文档归档
- ar -r libhello.a hello.o #这里的ar相当于tar的作用,将多个目标打包。
ar -r libhello.a hello.o #这里的ar相当于tar的作用,将多个目标打包。程序ar配合参数-r创建一个新库libhello.a,并将命令行中列出的文件打包入其中。这种方法,如果libhello.a已经存在,将会覆盖现在文件,否则将新创建。
3.链接静态库
- gcc main.c -lhello -L. -static -o main
gcc main.c -lhello -L. -static -o main这里的-static选项是告诉编译器,hello是静态库。
或者:
- gcc main.c libhello.a -L. -o main
gcc main.c libhello.a -L. -o main这样就可以不用加-static
4.执行./main
输出:call hello()
0 0
- GCC 编译动态库和静态库
- GCC 编译动态库和静态库
- GCC 编译动态库和静态库
- gcc 编译动态库和静态库
- gcc编译静态库和动态库
- gcc编译静态库和动态库
- gcc编译静态库和动态库
- gcc 编译动态库和静态库
- GCC 编译动态库和静态库
- gcc编译静态库和动态库
- GCC编译静态库和动态库
- GCC 编译动态库和静态库
- gcc编译静态库和动态库
- gcc编译静态库和动态库
- gcc编译动态库和静态库
- gcc 编译动态库和静态库
- gcc编译动态和静态链接库
- gcc编译动态和静态链接库
- Java Collections Framework之TreeMap源码分析(基于JDK1.6)
- 想网站与目标站点同步更新?利用采集侠轻松实现
- 远程桌面连接
- jdk版本不同引起的问题分析
- Android多线程任务优化1
- gcc编译静态库和动态库
- 甘肃科技文献共享平台架构及关键技术研究
- <meta>标签 http-equiv
- winImageSdk Simple
- 如何配置Microsoft Windows XP远程桌面
- 《Apache MINA 2.0 用户指南》第十六章:JMX 集成
- iPhone检测是否存在耳麦
- Cocos2d-x中应用C++11正则表达式检验邮箱地址(跨平台)
- Amoeba for mysql读写分离