一、首先,為兩個函數分別建立各自的源檔案(將他們分別命名為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