概述

库:库是事先编译好的, 可以复用的二进制代码文件。包含的代码可被程序调用

 

Linux下包含静态库和共享库

静态库特点:编译(链接)时把静态库中相关代码复制到可执行文件中

动态库特点:编译(链接)时仅记录用到哪个共享库中的哪个符号, 不复制共享库中相关代码

 

静态库

 

1.静态库创建

编写库源码hello.c

void hello(void) {
printf(“hello world\n”);
return;
}

编译生成目标文件

 

$ gcc -c hello.c -Wall

创建静态库

$ ar crs libhello.a hello.o

可查看库中符号信息

$nm libhello.a

 

 

 

2.链接静态库

 

编写应用程序test.c

#include <stdio.h>
void hello(void);
int main() {
hello();
return 0;
}

编译test.c 并链接静态库libhello.a

$ gcc -o test test.c -L. -lhello
$ ./test

上面的命令中 -L. 告诉 gcc 搜索链接库时包含当前路径, -lhello 告诉 gcc 生成可执行程序时要链接 hello.a

 

共享库

 

共享库创建

 

编写库源码hello.c

#include <stdio.h>
void hello(void) {
printf(“hello world\n”);
return;
}

编译生成目标文件

$ gcc -c -fPIC hello.c bye.c -Wall
  • fPIC是使生成的目标文件“位置无关(Position Independent Code)”从而可以被多个程序共享。

创建共享库 common

 

$ gcc -shared -o libcommon.so.1 hello.o 

 

 

为共享库文件创建链接文件

$ ln -s libcommon.so.1 libcommon.so

PS:符号链接文件命名规则  lib<库名>.so

 

 

 

 

链接共享库

#include <stdio.h>
void hello(void);
int main() {
hello();
bye();
return 0;
}

 

编译test.c 并链接共享库libcommon.so

$ gcc -o test test.c -L. -lcommon

 

执行程序

./test
./test: error while loading shared libraries: libcommon.so
cannot open shared object file : No such file or directory 

 

这是系统没有找到共享库文件,有三种解决方案

1.把库拷贝到/usr/lib和/lib目录下

2.在LD_LIBRARY_PATH环境变量中添加库所在路径

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.

3.添加/etc/ld.so.conf.d/*.conf文件, 执行ldconfig刷新

 

sudo vim //etc/ld.so.conf.d/my.conf
写入你的共享库的绝对路径
sudo ldconfig

推荐方法3。