聘我网

新概念招聘3.0

如何加载某个ld还无法找到的so文件?

vote up0vote downstar

做了个动态链接库,现在要测试其功能,又不想立马放到ld的搜索路径去,有什么临时解决之法?

 

1 个答复

vote up0vote downcheck

修改LD_LIBRARY_PATH环境变量。

例子:

[root@dev-test swig]$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. ./test_lib
6

附上一个生成使用动态库的小例子:

[root@dev-test swig]$ cat lib_shore.c
#include <stdio.h>
#include "lib_shore.h"

int add_shore(int a, int b){
  return a+b;
}

[root@dev-test swig]$ cat lib_shore.h
int add_shore(int, int);

[root@dev-test swig]$ cat test_lib.c
#include <stdio.h>
#include "lib_shore.h"

int main(int argc, char* argv[])
{
    printf("%d\n", add_shore(1,5));
}

编译方法:

[root@dev-test swig]$ gcc -fPIC -shared lib_shore.c -o lib_shore_raw.so
[root@dev-test swig]$ gcc test_lib.c -o test_lib -L. -l_shore_raw
[root@dev-test swig]$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. ./test_lib
6

更新

[root@dev-test swig]$ gcc test_lib.c -o test_lib -L. -l_shore_raw

也可以写得更直接一些:

[root@dev-test swig]$ gcc test_lib.c lib_shore_raw.so -o test_lib

更好的办法

link时指定rpath参数的话,运行时就不需要再额外指定了:

CC            = gcc 
CFLAGS        = -Wall

lib_shore: lib_shore.c
    $(CC)  $(CFLAGS) -fPIC -shared  -o "$@.so" "$<"
test_lib: test_lib.c                                                            
    $(CC)  $(CFLAGS) -o "$@" "$<" -L. -l_shore -Wl,-rpath,'$$ORIGIN'

其中$ORIGIN表示运行时可执行文件所在目录。

参考:

Using ORIGIN for a dynamic runtime library search path

链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.