1. 程式人生 > >Linux環境下靜態庫的生成和使用 (.a檔案)

Linux環境下靜態庫的生成和使用 (.a檔案)

        這一陣子的工作用到了linux,也用到了linux的靜態庫和動態庫。正好對這一塊兒一直不明白,趁此機會學習了一下。以下是筆記。先說一說linux下靜態庫的生成和使用方法。

     An archive (or static library) is simply a collection of object files stored as a single file.(An archive is roughly the equivalent of a Windows .LIB file.) When you provide an archive to the linker, the linker searches the archive for the object files it needs, extracts them, and links them into your program much as if you had provided those object files directly. 

     You can create an archive using the ar command.Archive files traditionally use a .a extension rather than the .o extension used by ordinary object files. Here’ s how you would combine test1.o and test2.o into a single libtest.a archive:

% ar cr libtest.a test1.o test2.o

     The cr flags tell ar to create the archive.

                                                                             ---摘自《Advanced Linux Programming》

由上面可以看到,linux作業系統中,
1.靜態庫是一些目標檔案(字尾名為.o)的集合體而已。
2.靜態庫的字尾名是.a,對應於windows作業系統的字尾名為.lib的靜態庫。
3.可以使用ar命令來建立一個靜態庫檔案。
來看一個例項,根據書中的程式碼簡化的,先看一看可以編譯成庫檔案的原始檔中的程式碼:


  
  1. /* test.c */
  2. int f()
  3. {
  4. return 3;
  5. }

程式碼非常簡單,只有一句話。我們敲入如下命令:
gcc –c test.c
ar cr libtest.a test.o
會在當前目錄下生成一個libtest.a靜態庫檔案。-c表示只編譯,不連結。再來看一看如何使用這個庫。如下程式碼:


  
  1. /* app.c */
  2. #include <stdio.h>
  3. extern int f();
  4. int main()
  5. {
  6. printf(“ return value is %d\n”,f());
  7. return 0;
  8. }

敲入如下命令:
gcc –c app.c
gcc -o app app.o -L. –ltest
敲命令的時候要記得將libtest.a檔案和生成的app.o檔案放在同一個目錄(即當前目錄)下。這樣,敲入命令後,會在當前目錄下生成一個名為app的可執行檔案。-o表示指定輸出檔名。執行一下./app,可以看一看結果:

這就是生成linux下面靜態庫的簡單用法了。