特定地址的外部变量

And*_*iNo 4 c c++

使用C++和GCC,我可以声明一个在内存中使用特定地址的extern变量吗?就像是

int key __attribute__((__at(0x9000)));
Run Code Online (Sandbox Code Playgroud)

AFAIK此特定选项仅适用于嵌入式系统.如果在x86平台上有这样的选项,我该如何使用它?

Art*_*ius 12

简单的选择:

限定

int * const key = (int *)0x9000;
Run Code Online (Sandbox Code Playgroud)

并参考*key其他地方(或使用参考).

无指针选项:

所有的外部都有特定的地址!这些地址可能在链接时才知道,但最终必须得到解决.如果您声明extern int key;那么您必须key在链接时提供符号的地址.这可以使用链接描述文件(请参阅使用ld)或链接器命令行使用该--defsym选项完成.

如果运行gcc,您可以使用该-Xlinker标志将选项传递给链接器.在你的例子中,

gcc -o outfile -Xlinker --defsym -Xlinker key=0x9000 sourcefile.c
Run Code Online (Sandbox Code Playgroud)

由此编制的以下程序输出0x9000.

#include <stdio.h>
extern int key;
int main(void) {
    printf("%p\n", &key);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要在某个内存区域中拥有一组变量,那么更合适的方法可能是使用Nikolai建议的输出节,也许与自定义ld脚本结合使用.

  • 这就是我一直在寻找的。我正在使用 DLL 注入来反转程序。在我的 DLL 代码中,我必须访问属于目标进程的变量。为了在没有指针的情况下访问它们,我需要某种方法来为 extern 变量提供特定地址。谢谢! (2认同)