Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 靜態庫的建立與使用

Linux 下的庫分兩種:靜態庫與共享(動態)庫,兩者的主要差別在於連接到程式的過程。編譯程式時,連結器(ld)負責把不同模組連接起來產生最終的可執行檔。靜態庫正是在這一階段被連接進程式,成為程式的一部分;共享庫則不同,編譯時加入程式的只是一些鉤子,直到程式執行時才把共享庫載入。

建立與使用靜態庫

建立靜態庫通常使用 ar 程式把一些目標檔(.o)組合為單一庫檔,再執行 ranlib 加入索引資訊。以下用一個基本的 hello world 程式示範。

say_hello.h:

#ifndef _SAY_HELLO_
#define _SAY_HELLO_

void say_hello ();

#endif

say_hello.cpp:

#include "say_hello.h"
#include <iostream>

using std::cout;

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

say_world.h:

#ifndef _SAY_WORLD_
#define _SAY_WORLD_

void say_world ();

#endif

say_world.cpp:

#include <iostream>
#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 ();
}

生成庫並使用的步驟如下:

1、用 g++ -c 產生目標檔:

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

2、用 ar rc 歸檔為庫檔:

ar rc libhelloworld.a say_hello.o say_world.o

3、用 ranlib 產生索引:

ranlib libhelloworld.a

4、使用庫:

g++ -o main main.cpp -L. -lhelloworld

其中 -L. 告訴連結器在目前目錄查找庫檔;-l 選項指定要連結的庫,這裡省略前綴 lib 與後綴 .a。

相關鏈接:Linux 動態庫的建立和使用 https://www.linuxidc.com/Linux/2013-03/81084.htm

Copyright © Linux教程網 All Rights Reserved