Linux下的库有两种:动态库和静态库,二者的不同点在于代码被载入的时刻不同.
静态库对函数库的链接是放在编绎时期完成的(compile time).
动态库把对一些库函数的链接推迟到程序运行的时期(run time).
创建静态库(libXXX.a):
建立 printHello.c printHello.h 文件
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ gcc -c printHello.c -o printHello.o //生成.o文件
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ ar crs libprintHello.a printHello.o //生成.a文件命名规范:libXXX.a
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ gcc testPrintHello.c -o testPrintHello -L. -lprintHello //编绎,生成可执行文件
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ ls
core libprintHello.a printHello.c printHello.h printHello.o testPrintHello testPrintHello.c
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ ./testPrintHello
hello,(null)
ubuntu@ubuntu-virtual-machine:~/unix/staticLib$ ./testPrintHello go
hello,go
创建动态库(libXXX.so):
建立printHello.c printHello.h文件
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ gcc -fPIC -c printHello.c //PIC创建与地址无关的编绎程序
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ ls
core printHello.c printHello.h printHello.o test.c
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ gcc printHello.o -shared -o libprintHello.so
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ ls
core printHello.c printHello.h printHello.o libprintHello.so test.c
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$
执行要用到此动态库的文件,得让系统可以找到.so文件,有三种方法
1.把库拷贝到/usr/lib或/lib下
2.在 LD_LIBRARY_PATH环境变量中加上库所在路径
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ export LD_LIBRARY_PATH=`pwd`
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ echo $LD_LIBRARY_PATH
/home/ubuntu/unix/sharedLib
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$
3.添加配置文件,再用ldconfig刷新
ubuntu@ubuntu-virtual-machine:/etc/ld.so.conf.d$ ls
GL.conf i686-linux-gnu.conf libasound2.conf libc.conf my.conf vmware-tools-libraries.conf
ubuntu@ubuntu-virtual-machine:/etc/ld.so.conf.d$ sudo ldconfig
[sudo] password for ubuntu:
ubuntu@ubuntu-virtual-machine:/etc/ld.so.conf.d$ cat my.conf
/home/ubuntu/unix/sharedLib
执行程序
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ gcc test.c -lprintHello -o printHello
/usr/bin/ld: cannot find -lprintHello
collect2: ld returned 1 exit status
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ gcc test.c -L. -lprintHello -o printHello
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$ ./printHello success
hello,success
ubuntu@ubuntu-virtual-machine:~/unix/sharedLib$