您的位置:首页 > 运维架构 > Linux

Linux下建立静态库的实例讲解

2009-12-09 10:30 453 查看
关于[/b]Linux[/b]下建立一个静态库的简要步骤:[/b][/b]
静态库,也称作归档文件,通常他们的文件名以“.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本文出自 “飞雪待剑” 博客,请务必保留此出处http://jazka.blog.51cto.com/809003/240509
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: