kyk*_*yku 1 gcc dlopen weak-linking
您好,我有一个具有全局函数的程序,我想在运行时对其进行自定义。比如说,有许多版本的函数 foo() 分散在共享库中。现在,基于在运行时检测到的系统配置,我想使用适当库中的函数。
文件加载器.cpp:
#include <dlfcn.h>
#include <iostream>
void __attribute__((weak)) foo();
int main(int argc, char *argv[])
{
void* dl = dlopen("./other.so", RTLD_NOW | RTLD_GLOBAL);
if (!dl)
{
std::cerr << dlerror() << std::endl;
return 1;
}
if (foo)
{
foo();
}
else
{
std::cerr << "No foo?" << std::endl;
}
dlclose(dl);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
文件其他.cpp:
#include <iostream>
void foo()
{
std::cout << "FOO!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我编译程序
g++ -Wall -fPIC -o loaded loader.cpp -ldl
g++ -Wall -fPIC -shared -o other.so other.cpp
Run Code Online (Sandbox Code Playgroud)
但是,弱符号不会被覆盖。任何提示?
符号在引用它们的图像的加载期间解析。所以当你的可执行文件被加载时,对 foo 的引用已经被解析。稍后的 dlopen 不会重新绑定所有符号 - 它只会影响以后的加载。
您必须改用 dlsym,或设置 LD_PRELOAD:
martin@mira:/tmp$ LD_PRELOAD=/tmp/other.so ./loaded
FOO!
Run Code Online (Sandbox Code Playgroud)