创建静态库的步骤:
1. 创建并编写源文件;
2. 使用gcc -c命令生成需要包含在库文件中的目标文件;
3. 为库函数创建一个头文件,声明库文件中的函数;
4. 测试目标文件是否正确;
5. 用ar程序创建一个归档文件并将你斗目标文件添加进去;
6. 用ranlib命令为函数库生成一个内容表(不是必须);
7. 测试库文件。
例如:
1.创建bill.c和fred.c文件,内容分别为:
// bill.c
#include <stdio.h>
void bill(char *arg)
{
printf("bill: we passed %s \n", arg);
}
// fred.c
#include <stdio.h>
void fred(int arg)
{
printf("fred: we passsed %d.\n ,arg");
}
2. 编译成目标文件:
gcc -c bill.c fred.c
3. 创建头文件,声明函数:
// bill .h
#ifndef BILL_H
#define BILL_H
void bill(char *);
void fred(int);
#endif
4. 测试目标文件是否正确:
// main.c
#include <stdlib.h>
#include "bill.h"
int main()
{
bill("Hello World");
fred(10);
exit(0);
}
gcc -c main.c
gcc -o main.o fred.o bill.o
5. 用ar程序创建一个归档文件并将目标文件添加进去
ar crv libfoo.o bill.o fred.o
6. 测试文件:
gcc -o main main.c -L. -lfoo
附加:
可以利用nm命令查看哪些函数被包含在目标文件、函数库或者可执行文件里。
可以利用ldd命令来查看程序需要得共享库,例如: ldd main