Linux下模組化編程產生函數庫和編譯方法

來源:互聯網
上載者:User

一、首先,為兩個函數分別建立各自的源檔案(將他們分別命名為fred.c和bill.c).下面第一個源檔案:

#include "stdio.h"

void fred(int arg)

{

printf("fred: we passed %d\n",arg);

}

下面是第二個源檔案:

#include "stdio.h"

void bill(char *arg)

{

printf("bill:we passed %s\n",arg);

}

二、分別編譯這些函數以產生要包含在庫檔案中的目標檔案。

$ gcc -c bill.c fred.c

三、現在編寫一個調用bill函數的程式。首先為你的庫檔案建立一個標頭檔。這個標頭檔將聲明你的庫檔案中的函數,他應該被希望所有希望使用你的庫檔案的應用程式所包含。

/*This is lib.h It declares the functions fred and bill for users */

void bill(char *);

void fred(int);

四、調用程式(program.c)非常簡單,它包含庫的標頭檔並且調用庫中的一個函數。

#include "lib.h"

int main()

{

bill("hello world");

exit(0);

}

五、現在你可以編譯並測試這個程式了。你暫時為編譯器顯示指定目標檔案,然後要求編譯器編譯你的檔案並將其與先前編譯好的目標模組bill.o連結。

$ gcc -c program.c

$ gcc -o program program.o bill.o

$ ./program

bill : we passed hello word

$

六、現在,你將建立並使用一個庫檔案。使用ar 程式建立一個歸檔檔案並將你的目標檔案添加進去。

$ ar crv libfoo.a bill.o fred.o

a - bill.o 

a - fred.o

七、庫檔案建立好了,兩個目標檔案都添加進去了,要想成功使用函數庫,你還需要為函數庫產生一個內容表。可以用ranlib 命令來完成這一工作。

$ ranlib libfoo.a

這個函數庫就可以使用了,你可以在編譯器使用的檔案清單中添加該庫檔案以建立你的程式

$ gcc -o program  program.o libfoo.a

./proram

bill : we passed hello world 

$

你也可以使用-l選項來訪問函數庫,但其未儲存在標準位置,所以必須使用-L選項來告訴編譯器在何處可以找到他,

$ gcc -o program program.o -L. -lfoo


相關文章

聯繫我們

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