链接期和运行期的动态链接库

来源:互联网 发布:会员名和淘宝昵称区别 编辑:程序博客网 时间:2024/05/01 12:23

可执行文件在查找依赖的动态链接库时,是根据 /etc/ld.so.conf 和 $LD_LIBRARY_PATH 查找的。

所以,换了机器运行(如开发机和线上机),链接到的共享库可能不一致。

另外,链接期可以hard code所要链接的库的路径。这样,即使换了机器,运行期也会从hard code的路径去寻找库。


例子:

开发机上:

server.h

void fun();

server.c

#include <stdio.h>void fun() {  printf("server fun.");}

server_2.c

#include <stdio.h>void fun() {  printf("server fun.");  printf("server fun.");  printf("server fun.");  printf("server fun.");  printf("server fun.");  printf("server fun.\n");}


test.c

#include "server.h"#include "stdio.h"int main() {  fun();}

命令:

gcc server.c -shared -fPIC -o libserver.so
gcc test.c -L. -lserver -o test
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"current_path"
./test
=====output: server fun.

将这些文件放到另外一台机器上

mv libserver_2.so libserver.so
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"current_path_on_this_machine"
./test
=====output:  server fun.server fun.server fun.server fun.server fun.server fun.

另外,如果在编译test时使用libserver.so的绝对路径:

gcc test.c current_path/libserver.so -o test
那么,另外一台机器上运行时,如果 current_path 和 current_path_on_this_machine 不同,则报错:

./test: error while loading shared libraries: current_path/libserver.so: cannot open shared object file: Permission denied



0 0