设为首页 加入收藏

TOP

Linux 静态库的创建和使用
2014-11-24 08:05:36 来源: 作者: 【 】 浏览:0
Tags:Linux 静态 建和 使用

简介


在linux下库分两种:静态库和共享(动态)库。这两种库的主要不同在于连接到程序的过程。


在编译程序时,连接器(ld)负责把程序中不同的模块连接起来,产生最终的可执行文件。静态库就是在这一过程连接到程序,成为程序的一部分。共享库与此不同,在编译时加入程序的只是一些钩子,在程序运行的时候才需要把共享库调入以便运行。


创建和使用静态库
创建静态库:通常使用ar程序把一些目标文件(.o)组合在一起,成为一个单独的库,然后运行ranlib,以给库加入一些索引信息。


在本节使用如下的代码完成一个基本hello wold程序:


say_hello.h


#ifndef _SAY_HELLO_
#define _SAY_HELLO_


void say_hello ();


#endif



say_hello.cpp


#include "say_hello.h"
#include


using std::cout;


void say_hello ()
{
cout << "hello ";
}



say_wolrd.h


#ifndef _SAY_WORLD_
#define _SAY_WORLD_


void say_world ();


#endif



say_world.cpp


#include
#include "say_world.h"


using std::cout;
using std::endl;


void say_world ()
{
cout << "world" << endl;
}



main.cpp


#include "say_hello.h"
#include "say_world.h"


int main ()
{
say_hello ();
say_world ();
}



生成库和使用库的步骤如下:
使用g++ -c生成目标文件(.o)


g++ -c -o say_hello.o say_hello.cpp
g++ -c -o say_world.o say_world.cpp



使用ar rc归档为库文件


ar rc libhelloworld.a say_hello.o say_world.o



使用ranlib生成索引


ranlib libhelloworld.a



使用库


g++ -o main main.cpp -L. -lhelloworld
-L. 告诉连接器在当前目录查找库文件;-l 选项指定连接的库,这里省略前缀lib和文件名后缀.a


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇如何在Android应用中使用已有的SQ.. 下一篇Android ListView 的下拉刷新【附..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)
·整理了250个shell脚 (2025-12-26 07:53:29)
·HyperText Transfer (2025-12-26 07:20:48)
·半小时搞懂 HTTP、HT (2025-12-26 07:20:42)