感谢您的所有回复。我有一个似乎有效的解决方案。这是一个带有示例的详细问题。
在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的工作量更大,但这确实解决了我的问题。
再次感谢您的评论。



