下面是目录结构:
pengdl@localhost:~$ tree test/
test/
├── fun.c
├── Fun.h
└── t1
└── main.c
1 directory, 3 files
pengdl@localhost:~$
fun.c
#include <stdio.h> void fun(void) { printf("int the fun "); }
Fun.h
extern void fun(void);
main.c
#include <stdio.h> #include <Fun.h> int main(int argc, const char *argv[]) { printf("in the main "); fun(); return 0; }
在test目录下,制作动态库:
pengdl@localhost:~/test$ ls
fun.c Fun.h t1
pengdl@localhost:~/test$ gcc -fPIC -c fun.c
pengdl@localhost:~/test$ ls
fun.c Fun.h fun.o t1
pengdl@localhost:~/test$ gcc -shared fun.o -o libfun.so.1
pengdl@localhost:~/test$ ls
fun.c Fun.h fun.o libfun.so.1 t1
pengdl@localhost:~/test$ ln -s /home/pengdl/test/libfun.so.1 libfun.so
注意:软连接必须指向刚才生产的库,否则链接是会出错!!
pengdl@localhost:~/test$ ls
fun.c Fun.h fun.o libfun.so libfun.so.1 t1
pengdl@localhost:~/test$ mv libfun.so t1/
执行: gcc main.c -o main -lfun -L ./ -I ../
注:其中 -L ./是在链接是告诉链接器动态库的搜索路径,因为动态库的软连接在当前目录下,所以需要 -L ./ ,否则链接时因为找不到库而出错。-L ./只是告诉链接器在链接时还需要到当前目录下搜索,并不会覆盖其他库的搜索路径。
pengdl@localhost:~/test/t1$ gcc main.c -lfun -I ../ -L ./
pengdl@localhost:~/test/t1$ ./a.out
./a.out: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory
pengdl@localhost:~/test/t1$
原因:没有将共享库libfun.so.1拷贝到/uer/lib下,如果拷到/usr/lib下,软连接libfun.so也应该改变。解决方法二:在链接时指定运行时库的搜索路径:gcc main.c -lfun -I ../ -L ./ -Wl,-rpath=./。解决方法三:修改/etc/ld.so.cache中所缓存的动态库路径(如果支持ld.so.cache的话)。这可以通过修改配置文件/etc/ld.so.conf中指定的动态库搜索路径来改变;