源文件:mytestlib.c
#include "mytestlib.h"
int Add(int a ,int b)
{
return a+b;
}
int Sub(int a,int b)
{
return a-b;
}
1.静态库的创建和使用
a.编译mytestlib.c生成目标文件:gcc -o mytestlib.o -c mytestlib.c
f.运行可执行程序mytest: ./mytest
hello ,welcome to mytest!
5+3=8
5-3=2
2.创建生成动态库
a.编译生成动态库
gcc mytestlib.c –fPIC –shared –o libmytestlib.so
由以上命令生成动态库libmytestlib.so
–fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,
而不能达到真正代码段共享的目的。
–shared:指明编译成动态库。
b.使用动态库编译命令:
gcc mytest.c –L . –l mytestlib –o mytest
–L:指明动态库所在的目录
-l:指明动态库的名称,该名称是处在头lib和后缀.so中的名称,如上动态库libtest.so的l参数为-l test。
c. 查看程序使用动态库情况:
ldd mytest
注: ldd 测试可执行文件所使用的动态库
d.将动态库copy到Linux的库目录(/usr/lib或者/lib)下:cp libmytestlib.so /usr/lib/libtestmylib.so
e.运行可执行程序mytest: ./mytest
hello ,welcome to mytest!
5+3=8
5-3=2