1、静态库 《来自博客:http://blog.csdn.net/stpeace/article/details/47030017》
步骤一:
写test.h文件, 内容为:
- void print();
写test.c文件, 内容为:
- #include <stdio.h>
- #include "test.h"
- void print()
- {
- printf("I am a little bit hungry now.\n");
- }
步骤二:制作静态链接库, 如下:
- [taoge@localhost learn_c]$ ls
- test.c test.h
- [taoge@localhost learn_c]$ gcc -c test.c
- [taoge@localhost learn_c]$ ls
- test.c test.h test.o
- [taoge@localhost learn_c]$ ar rcs libtest.a test.o //注释: ar -r libtest.a test.o 亦可
- [taoge@localhost learn_c]$ ls
- libtest.a test.c test.h test.o
- [taoge@localhost learn_c]$
步骤三: 给客户提供libtest.a和test.h(二者缺一不可), 然后收钱, 收入为1毛。
好了, 现在客户花了1毛钱买到了静态链接库和对应的头文件, 也就是ibtest.a和test.h, 那他怎么用呢?
步骤一:
先写应用程序main.c, 内容为:
- #include "test.h"
- int main()
- {
- print();
- return 0;
- }
步骤二: 支付1毛钱, 获取静态链接库libtest.a和test.h, 并用它们, 如下(我删除了除去main.c, libtest.a和test.h之外的所有东东):
- [taoge@localhost learn_c]$ ls
- libtest.a main.c test.h
- [taoge@localhost learn_c]$ gcc main.c -L. -ltest
- [taoge@localhost learn_c]$ ./a.out
- I am a little bit hungry now.
- [taoge@localhost learn_c]$ rm libtest.a test.h
- [taoge@localhost learn_c]$ ./a.out
- I am a little bit hungry now.
- [taoge@localhost learn_c]$
2、 动态库
仿照 上面的例子, 我们 可以用同样的 例子 来写一下 动态库的 生成 方式
同样的文件 test.h test.c
编译共享库有两部分:
1、 编译成位置独立代码的目标文件 -fpic
2、 编译成共享库,选项 -shared
· gcc -c fpic test.c
. gcc -shared test.o -o libtest.so
3、 使用一条指令的效果:
. gcc -fpic -shared test.c -o libtest.so
4、 使用共享库:
/usr/lib -- 一般作为用户库 存放路劲。
/usr/local/include---存放头文件 位置 一般用 -I 参数指定