关于 Linux 下建立一个静态库的简要步骤: <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

静态库,也称作归档文件,通常他们的文件名以“ .a ”结尾。

 

下面我们来创建一个小型的函数库,包含两个函数。

第一, 创建函数源文件,如 fred.c bill.c
/*************fred.c***************/
#include <stdio.h>
void fred(int arg)
{    
     printf(“fred: you    passed    %d\n”,    arg);    
}
/*************bill.c***************/
#include <stdio.h>
void bill(char *arg)
{    
    printf(“bill: you    passed    %s\n”,    arg);    
}
第二 ,分别编译两个函数,产生要包含在库文件中的目标文件,即获得 fred.o bill.o:

              gcc  -c  bill.c  fred.c

 

第三 ,创建库文件 lfoo.a

              ar  crv  lfoo.a  bill.o  fred.o

 

第四 ,为库文件创建一个头文件 lib.h ,为调用程序做准备:

/* This is a lib.h.*/
void fred(int arg);
void bill(char *);
 
第五 ,编写调用程序 test.c
#inlcude    <lib.h>
int    main()
{
        bill(“hello world!”);
        exit(0);
}
 
第六 ,编译运行:

(1) 生成目标文件 test.o cgcc  -c  test.c

(2) 生成可执行文件 test gcc  -o  test  test.o  lfoo.a

(3) 运行 test ./test

 
上述第六步,也可通过 -L 来连接静态库:

            gcc  -o  test  test.o  -L  -lfoo