使用符号表在C ++中按名称引用变量 [英] Reference a variable by name in C++ by using Symbol Table

查看:196
本文介绍了使用符号表在C ++中按名称引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上是标题要求的内容.

我不太了解C++和更高级的概念(例如符号表),因此我在线上对其进行了研究,但仍在努力寻找最终目标的任何方向.我见过的大多数教程都是针对C的,也是我发现的最接近的问题(解决方案

下面是一个示例程序,显示了如何使用dlsym查找符号:

#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";
}

extern "C"位可防止名称修改,以确保符号表条目只是传递给dlsym()"my_variable"文本.您不能使用extern "C"并提供错误的名称,但这将是特定于编译器的.

要编译代码,请使用:

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

-ldldlsym的库,并且-rdynamic要求不要放弃看似未使用的变量的符号信息(请参阅here) puts me at a brick wall, as I've tried compiling it but I'm not getting the desired results, and I'm not too solid on how extern "C" works yet.

By the end of this, I want to be able to access a variable from the symbol table, and change the variable. I have played around with nm and objdump (and coming from a hardware background, it's definitely cool to look at), and I looked into dlsym, dlopen, etc. but I'm not sure how that could help me (especially since I've seen it used in C more than anything else).

Any advice or small snippets of code (so I can write my own sample program) would be great. Just to add, this is on a Linux system with a sort of outdated version of G++ (I'm not on the machine right now so I don't have that information) and I don't have access to upgrade it right now.

解决方案

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

这篇关于使用符号表在C ++中按名称引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆