linux下动态链接库和静态链接库的使用和区别
2016-07-21 15:45
405 查看
字面意思上来看,一看是在程序运行的时候动态链接。而另一个是在编译的时候静态链接。
考虑下面的3个文件,hello.c,hello.h,main.c
hello.h
层次关系就是main.cpp中使用hello()这个函数。
如何让这个程序能够顺利运行呢?直接g++去编译main.cpp肯定步行,下面尝试以下方式:
(1)分别将hello.cpp,main.cpp编译成xx.o文件,而后进行链接
1.g++ -c hello.cpp编译形成hello.o
2.g++ -c main.cpp编译形成main.o
3.g++ main.o hello.o -o main形成科执行程序,而后运行无误。
(2)使用动态链接的方式
1.先将hello.cpp编译成一个动态链接库
g++ -shared -fPIC -o libhello.so hello.cpp 这个时候会生成一个libhello.so文件
2.g++ main.cpp -o main -L. -lhello 这个时候会生成一个main的可执行文件。但是还是不能运行,需要讲上一步生成的动态链接库文件拷贝到/usr/lib下
3.cp ./libhello.so /usr/lib
4.运行程序,这个时候便可以运行了
使用动态链接库的属性:
1.程序运行的时候才链接,因此如果修改动态链接库的话不需要重修修改编译程序。
2.由于是动态链接,因此原来的程序的大小要比使用静态链接库的时候小
(3)使用静态链接库
1.g++ -c hello.cpp编译形成hello.o
2.使用ar,创建静态库 ar -r libhello.a hello.o
3.编译的时候使用静态库 g++ main.cpp -o main -L. libhello.a
4.运行程序。正常
使用静态库的属性:
1.每次修改静态库部分需要重新编译整个程序
2.增加程序最后的大小
3.静态库代码在每一个使用静态库的程序中都存在一份副本
考虑下面的3个文件,hello.c,hello.h,main.c
hello.h
#ifndef _HELLO_H #define _HELLO_H void hello(); #endifhello.cpp
#include<iostream> using namespace std; void hello() { cout<<"hello world"<<endl; }main.cpp
#include<iostream> #include"hello.h" using namespace std; int main() { hello(); }
层次关系就是main.cpp中使用hello()这个函数。
如何让这个程序能够顺利运行呢?直接g++去编译main.cpp肯定步行,下面尝试以下方式:
(1)分别将hello.cpp,main.cpp编译成xx.o文件,而后进行链接
1.g++ -c hello.cpp编译形成hello.o
2.g++ -c main.cpp编译形成main.o
3.g++ main.o hello.o -o main形成科执行程序,而后运行无误。
(2)使用动态链接的方式
1.先将hello.cpp编译成一个动态链接库
g++ -shared -fPIC -o libhello.so hello.cpp 这个时候会生成一个libhello.so文件
2.g++ main.cpp -o main -L. -lhello 这个时候会生成一个main的可执行文件。但是还是不能运行,需要讲上一步生成的动态链接库文件拷贝到/usr/lib下
3.cp ./libhello.so /usr/lib
4.运行程序,这个时候便可以运行了
使用动态链接库的属性:
1.程序运行的时候才链接,因此如果修改动态链接库的话不需要重修修改编译程序。
2.由于是动态链接,因此原来的程序的大小要比使用静态链接库的时候小
(3)使用静态链接库
1.g++ -c hello.cpp编译形成hello.o
2.使用ar,创建静态库 ar -r libhello.a hello.o
3.编译的时候使用静态库 g++ main.cpp -o main -L. libhello.a
4.运行程序。正常
使用静态库的属性:
1.每次修改静态库部分需要重新编译整个程序
2.增加程序最后的大小
3.静态库代码在每一个使用静态库的程序中都存在一份副本
相关文章推荐
- 在CentOS 7上编译安装lamp
- CentOS 七 vs CentOS 6的不同
- 飞凌Fl2440 led驱动的移植
- linux信号机制与python信号量
- 小记——linux睡眠
- linux环境下配置github 远程仓库
- linux 查看CPU个数,核数
- linux环境下配置github远程仓库
- Linux下chkconfig命令详解
- Enable FileStore and DataStore for CKAN on CentOS6.8
- 通过局域网安装centos6.4
- Linux权限体系总结
- linux进程的堆栈空间_代码段(指令,只读)、数据段(静态变量,全局变量)、堆栈段(局部变量)、栈【转】
- Linux 特殊权限位
- Linux 权限基础说明
- 关于java应用MD5校验文件和linux下md5Linux校验文件结果一致问题。
- linux iostat 性能指标说明
- Linux发展编年表
- Linux程序包管理
- linux删除、读取文件原理