Reference a variable by name in C++ by using Symbol Table

不想你离开。 提交于 2019-12-01 23:51:20

Here's an example program that shows how to use dlsym to look up a symbol:

#include <dlfcn.h>
#include <iostream>

extern "C" int my_variable = 42;

int main()
{
    if (int* p = (int*)dlsym(NULL, "my_variable"))
        std::cout << "my_variable @" << p << ' ' << *p << '\n';
    else
        std::cout << "dlsym failed\n";
}

The extern "C" bit prevents name mangling, ensuring the symbol table entry is simply the "my_variable" text passed to dlsym(). You could not use extern "C" and provide a mangled name, but that would be compiler specific.

To compile the code, use:

g++ x.cc -o x -ldl -rdynamic

The -ldl is the library for dlsym, and -rdynamic asks not to discard symbol information for seemingly unused variables (see here):

-rdynamic Pass the flag -export-dynamic to the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses of dlopen or to allow obtaining backtraces from within a program

Output on my machine:

my_variable @0x401010 42

@TonyD has essentially the correct answer. For a more detailed discussion of how to use the shared libraries, this is a pretty decent tutorial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!