Linux下動態庫的產生及連結方法

來源:互聯網
上載者:User

最近在看《C專家編程》,看到第5章-對連結的思考,正好作為參考,對Linux下動態庫的產生及連結方法作一下總結。

Linux下動態庫檔案的副檔名為".so"(Shared Object)。按照約定,所有動態庫檔案名稱的形式是libname.so(可能在名字中加入版本號碼)。這樣,線程函數庫被稱作libthread.so。靜態庫的檔案名稱形式是libname.a。共用archive的檔案名稱形式是libname.sa。共用archive只是一種過渡形式,協助人們從靜態庫轉變到動態庫。

本文僅以簡單的例子介紹動態庫檔案的產生和連結方法。
作業系統:Debian/GNU Linux 2.6.21-2-686;
GCC版本:4.1.3

一、庫檔案及測試檔案代碼

庫檔案及測試檔案所在的目錄:/home/program/。

1.庫檔案名稱:myfunction.c

/*Author: Godbach
  E-mail: nylzhaowei@163.com
*/

#include
<stdio.h>
int
my_lib_function (void)
{
    printf ("Library routine called from libmyfunction.so!\n");
    return 0;
}

2.測試檔案名:test.c

#include
<stdio.h>
int main(void)
{
    my_lib_function();
    return 0;
}

二、動態庫的編譯方法

編譯庫檔案myfunction.c:

debian:/home/program# gcc -shared -o libmyfunction.so myfunction.c

如果編譯成功,會在/home/program/下產生動態庫檔案:libmyfunction.so。
這裡有兩點需要說明:
1.對Linux操作,一般都推薦在普通使用者模式下,如果需要超級使用者的許可權,則可以通過su root,輸入root使用者密碼切換。我是個人學習使用,同時又有很多的操作都要使用root使用者,因此就直接在root使用者下進行編譯。

2.編譯產生動態庫的命令為:gcc (-fpic) -shared -o libmyfunction.so myfunction.c
    -fpic 使輸出的對象模組是按照可重定位地址方式產生的。
    -shared指定把對應的源檔案產生對應的動態連結程式庫檔案。

三、動態庫的測試方法

編譯測試檔案test.c:

debian:/home/program# gcc -o test test.c /home/program/libmyfunction.so

成功編譯後,產生test檔案,運行test:

debian:/home/program# ./test

Library routine called from libmyfunction.so!

其中,gcc -o test test.c /home/program/libmyfunction.so的最後一個參數指定所連結庫檔案的絕對路徑。本例中庫檔案的絕對路徑為:/home/program/libmyfunction.so。

當然,如果想從系統的庫檔案路徑(通常系統函數庫的位於/usr/lib下)連結動態庫的話,可以先將產生的庫檔案拷貝至/usr/lib/下,然後再連結:

debian:/home/program# cp libmyfunction.so /usr/lib/

debian:/home/program# gcc -o test test.c -lmyfunction

debian:/home/program# ./test

Library routine called from libmyfunction.so!

這裡,對於連結的方法作一下解釋。對於gcc -o test test.c -lmyfunction中最後一個參數-lmyfunction, 可見傳給C編譯器的命令列參數並未提到函數庫的完整路徑名,甚至沒有提到在函數庫目錄中該檔案的完整名字!實際上,編譯器被告知根據選項-lmyfunction連結到相應的函數庫(/usr/lib下),函數庫的名字是libmyfunction.so, 也就是說,"lib"部分和檔案的副檔名被省略了,但在前面加了一個l。

轉自:http://blog.chinaunix.net/space.php?uid=10167808&do=blog&id=25921

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.