9

基于 unix 的系统中的延迟负载等效是多少。

我有一个代码foo.cpp,在使用 gcc 编译时,我将它链接到共享对象(总共三个 .so 文件。)。每个 .so 文件用于不同的选项。

./foo -v需要libversion.so ./foo -update需要libupdate.so

我需要这些库的符号应该只在运行时解析。

./foo -v即使 libupdate.so 库不存在也不应该中断。

它使用延迟加载选项(在 dll 的属性中)在 Windows 中工作。它在 Unix 系统中的等价物是什么。

选项在 UNIX 中会-lazy不会做同样的事情?如果是这样,在哪里包含这个选项:在 makefile 中还是在链接器 ld 中?

4

2 回答 2

3

See the reference on your system for dlopen(). You can manually open libraries and resolve external symbols at runtime rather than at link time.

Dug out an example:

int main(int argc, char **argv) {                 
    void *handle=NULL;                                 
    double (*myfunc)(double);                     
    char *err=NULL;                                  

    handle = dlopen ("/lib/libm.so.1", RTLD_LAZY);
    if (!handle) {                                
        err=dlerror();
        perror(err);
        exit(1);                                  
    }                                             

    myfunc = dlsym(handle, "sin");                
    if ((err = dlerror()) != NULL)  {           
        perror(err);
        exit(1);                                  
    }                                             

    printf("sin of 1 is:%f\n", (*myfunc)(1.));              
    dlclose(handle);            
    return 0;                  
}                                                 
于 2010-06-02T12:00:45.440 回答
1

我知道已经8年了,但仍然...

延迟加载在 GNU 系统上不支持开箱即用,但您可以通过创建一个小型静态存根来自己模仿它,该存根dlopen在第一次调用时(甚至在程序启动时)提供所有必要的符号和真正的实现。这样的存根可以手工编写,由项目特定的脚本或通过Implib.so 工具生成:

# Replace
$ gcc -o foo foo.c -lversion
# with
$ implib-gen.py libversion.so
$ gcc -o foo foo.c libversion.tramp.S libversion.init.c
于 2018-02-16T09:18:24.443 回答