Linux下製作靜態連結庫

來源:互聯網
上載者:User

靜態連結庫是在編譯時間刻由連結器使用的庫檔案,Linux下預設尾碼名為.a的檔案為靜態庫.靜態庫出現主要是為了方便調用一些常用的函數。

主要有兩步:

1.編譯源碼

2.製作庫

=====================================

以兩個簡單的源碼為例,示範靜態庫製作的具體流程

1.編譯源碼

hello_first.c

void hello_first(void)
{
 printf("hello first");
}

hello_second.c

void hello_second(void)
{
 printf("hello second");
}

編譯:

gcc -c hello_first.c -o hello_first.o

gcc -c hello_second.c -o hello_second.o

2.製作靜態庫

ar -r  libhello.a hello_first.o hello_second.o

具體調用庫執行個體

hello_main.c

#include <stdio.h>

void hello_first(void);

void hello_second(void);

int main()
{
 hello_first();
 hello_second();
 return 0;
}

編譯:

第一種方法:

gcc hello_main.c libhello.a -o hello_main

第二中方法:

拷貝libhello.a到/lib目錄下

gcc hello_main.c -lhello -o hello_main2

運行:

OK!靜態庫調用成功!!

思考:

靜態庫作用是什嗎?為甚麼要發明它?

1.靜態庫主要是用於方便程式員編程,將要使用的函數封裝成庫,只要告訴他們函數介面就可以了,這樣程式員只要知道怎麼調用就行了。而廠家可以保持介面不變,而對代碼進行修改維護。

2.另外有可能是程式員自己將自己經常用到的函數封裝起來,不用重複編寫,只需調用前聲明下就OK.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.