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

linux下动态链接库和静态链接库的使用和区别

2016-07-21 15:45 405 查看
字面意思上来看,一看是在程序运行的时候动态链接。而另一个是在编译的时候静态链接。

考虑下面的3个文件,hello.c,hello.h,main.c

hello.h

#ifndef _HELLO_H
#define _HELLO_H
void hello();
#endif
hello.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.静态库代码在每一个使用静态库的程序中都存在一份副本
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: