之前, 我们讨论过如何在Windows下写静态链接库、动态链接库并卖给别人。 今天, 我们我们来说说如何在linux下写静态链接库并卖给别人。 一个屌丝程序员, 要制作个静态库, 卖给别人, 那要如何做、如何卖呢?
步骤一:
写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
[taoge@localhost learn_c]$ ls
libtest.a test.c test.h test.o
[taoge@localhost learn_c]$
看到没, 这就生成了libtest.a静态链接库。 当然, 制作者有必要对这个库进行测试, 但鉴于上面程序比较简单且测试并非本文主要讨论的东东, 所以略之。 注意, 上面libtest.a文件名是有要求的, 暂时不表。
步骤三: 给客户提供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]$
可以看到, 生成a.out后, 即使去掉了libtest.a和test.h, 也毫无关系, 因为这些都已经嵌入到a.out中了, 这就是所谓的静态链接库的作用。 那gcc如何查找静态库呢?当gcc看到-ltest的时候, 会自动去找去找libtest.a, 刚好, 我们有这个文件(对文件名有要求), 所以OK. 顺便说一下, 参数-L添加静态链接库文件搜索目录, 上面指定的是当前目录。
说明一下, 在制作静态连接库的时候, 我们用了ar rcs, 那如何查看某个静态链接库的依赖呢? 如下:
[taoge@localhost learn_c]$ ar -t libtest.a
test.o
[taoge@localhost learn_c]$
麻雀虽小, 五脏俱全。 本文先介绍到这里。 收拾收拾, 要睡觉了。