栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

链接库的多个版本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

链接库的多个版本

感谢您的所有回复。我有一个似乎有效的解决方案。这是一个带有示例的详细问题。

在main.c中,我们有:

#include <stdio.h>extern int foo();int bar(){    printf("bar in main.c calledn");    return 0;}int main(){    printf("result from foo is %dn", foo());    printf("result from bar is %dn", bar());}

在foo.c中,我们有:

extern int bar();int foo(){    int x = bar();    return x;}

在bar.c中,我们有:

#include <stdio.h>int bar(){    printf("bar in bar.c calledn");    return 2;}

编译bar.c和foo.c:

$ gcc -fPIC -c bar.c$ gcc -fPIC -c foo.c

将bar.o添加到静态库中:

$ ar r libbar.a bar.o

现在使用foo.o创建一个共享库,并与静态libbar.a链接

$ gcc -shared -o libfoo.so foo.o -L. -lbar

编译main.c并与共享库libfoo.so链接

$ gcc -o main main.c -L. -lfoo

设置LD_LIBRARY_PATH以找到libfoo.so并运行main:

$ setenv LD_LIBRARY_PATH `pwd`$ ./mainbar in main.c calledresult from foo is 0bar in main.c calledresult from bar is 0

注意,将调用main.c中的bar版本,而不是链接到共享库中的版本。

在main2.c中,我们有:

#include <stdio.h>#include <dlfcn.h>int bar(){    printf("bar in main2.c calledn");    return 0;}int main(){    int x;    int (*foo)();    void *handle = dlopen("libfoo.so", RTLD_GLOBAL|RTLD_LAZY);    foo = dlsym(handle, "foo");    printf("result from foo is %dn", foo());    printf("result from bar is %dn", bar());}

编译并运行main2.c(注意,我们不需要显式链接libfoo.so):

$ gcc -o main2 main2.c -ldl$ ./main2bar in bar.c calledresult from foo is 2bar in main2.c calledresult from bar is 0

现在,共享库中共享库调用栏中的foo和main.c中的主调用栏中

我不认为这种行为是直观的,使用dlopen / dlsym的工作量更大,但这确实解决了我的问题。

再次感谢您的评论。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/403220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号