制作动态库


动态库的制作举例

目标:创建一个小型函数库,该函数库包含两个函数,分别为:fred和bill

1)创建文件fred.c,内容如下:

#include <stdio.h>

void fred(int arg)
{
        printf("fred: you passed %d\n",arg);
}
2)创建文件bill.c,内容如下:

#include <stdio.h>

void bill(char *arg)
{
        printf("bill: you passed %s\n", arg);
}
3)分别编译上述两个文件

rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -c fred.c bill.c 
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ls *.o
bill.o  fred.o
rita@rita-desktop:~/linux_program/e1.1_static_lib$ 
4)编写一个程序,该程序调用bill函数。

4.1)先为要创建的库文件创建一个头文件lib.h(这个头文件将声明库文件中的函数) 

void fred(int);
void bill(char *);
4.2) 创建一个调用程序program.c,该程序包含库的头文件lib.h,并且调用库中的函数bill

#include "lib.h"

int main()
{
        bill("hello,world\n");
        return 0;
}
5)编译并测试program.c
 方法一)不使用库文件,而是使用常规的目标模块链接方法。

rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -c program.c
rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -o program program.o bill.o
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ./program
bill: you passed hello,world

rita@rita-desktop:~/linux_program/e1.1_static_lib$
方法二)
5.1)先将fred.o和bill.o创建为一个动态库libfoo.so
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ld -shared -o libfoo.so fred.o bill.o
rita@rita-desktop:~/linux_program/e1.1_static_lib$ 

5.2)使用动态库libfoo.so,编译program.c
rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -o program program.c -L. -lfoo
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ./program
./program: error while loading shared libraries: libfoo.so: cannot open shared object file: No such file or directory
rita@rita-desktop:~/linux_program/e1.1_static_lib$
因为在环境变量LD_LIBRARY_PATH中找不到libfoo.so,所以运行出错。
存在动态库时,需要设置环境变量LD_LIBRARY_PATH:
rita@rita-desktop:~/linux_program/e1.1_static_lib$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ./program
bill: you passed hello,world


rita@rita-desktop:~/linux_program/e1.1_static_lib$
其中,. 为当前目录
至此,表明成功创建了属于自己的动态库!!!
rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -o program program.c -lfoo
/usr/bin/ld: cannot find -lfoo
collect2: ld returned 1 exit status
rita@rita-desktop:~/linux_program/e1.1_static_lib$

因为库文件libfoo.a并没有保存在标准位置下,所有需要使用-L选项指定库文件所在位置。
rita@rita-desktop:~/linux_program/e1.1_static_lib$ gcc -o program program.c -L. -lfoo
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ./program
bill: you passed hello,world

rita@rita-desktop:~/linux_program/e1.1_static_lib$
至此,表明成功创建了属于自己的动态库!!!

6)ldd 命令:查看程序运行所需动态库
rita@rita-desktop:~/linux_program/e1.1_static_lib$ ldd program
linux-gate.so.1 => (0xb7765000)
libfoo.so => ./libfoo.so (0xb7761000)
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb75f2000)
/lib/ld-linux.so.2 (0xb7766000)
rita@rita-desktop:~/linux_program/e1.1_static_lib$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值