编译:gcc hello.c -fPIC -o libhello.so
gcc main.c -L. -lhello -o main
一、动态链接库
1.创建hello.so动态库
#include
void hello(){
printf("hello world\n");
}
编译:gcc -fPIC -shared hello.c -o libhello.so
void hello();
#include
#include "hello.h"
int main(){
printf("call hello()");
hello();
}
编译:gcc main.c -L. -lhello -o main
这里-L的选项是指定编译器在搜索动态库时搜索的路径,告诉编译器hello库的位置。"."意思是当前路径.
3.编译成够后执行./main,会提示:
In function `main':
main.c:(.text+0x1d): undefined reference to `hello'
collect2: ld returned 1 exit status
这是因为在链接hello动态库时,编译器没有找到。
sudo cp libhello.so /usr/lib/
这样,再次执行就成功输入:
二、静态库
文件有:main.c、hello.c、hello.h
1.编译静态库hello.o:
gcc hello.c -o hello.o #这里没有使用-shared
ar -r libhello.a hello.o #这里的ar相当于tar的作用,将多个目标打包。
程序ar配合参数-r创建一个新库libhello.a,并将命令行中列出的文件打包入其中。这种方法,如果libhello.a已经存在,将会覆盖现在文件,否则将新创建。
gcc main.c -lhello -L. -static -o main
这里的-static选项是告诉编译器,hello是静态库。
gcc main.c libhello.a -L. -o main
这样就可以不用加-static
4.执行./main
输出:call hello()
三、借助自带的ldd实现程序来分析动态库搜索情况
ldd main
结果:
linux-gate.so.1 => (0x00efd000)
libhello.so => /usr/lib/libhello.so (0x00f6b000)
libc.so.6 => /lib/libc.so.6 (0x001a5000)
/lib/ld-linux.so.2 (0x00eb8000)
如果目标程序没有链接动态库,则打印“not a dynamic executable”