在具体地址外部变量 [英] Extern variable at specific address

查看:166
本文介绍了在具体地址外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++和GCC,我可以宣布,在内存使用特定地址的外部变量?
类似

Using C++ and GCC, can I declare an extern variable that uses a specific address in memory? Something like

int key __attribute__((__at(0x9000)));

据我所知这个特定的选项仅适用于嵌入式系统。如果是在x86平台上使用这样的选择,我如何使用它?

AFAIK this specific option only works on embedded systems. If there is such an option for use on the x86 platform, how can I use it?

推荐答案

轻松选项:

定义

int * const key = (int *)0x9000;

和参照 *键其他地方(或使用参考)。

and refer to *key elsewhere (or use a reference).

Pointerless选项:

所有的实习医生有具体的地址!这些地址可能不知道,直到链接时,但他们必须得到最终解决。如果声明的extern INT键; ,那么你必须提供一个地址链接时符号。这可以使用连接器脚本来完成(见使用LD ),或在链接器命令行,使用 - defsym 选项

All externs have specific addresses! These addresses may not be known until link time, but they must get resolved eventually. If you declare extern int key; then you must supply an address for the symbol key at link time. This can be done using a linker script (see Using ld) or at the linker command line, using the --defsym option.

如果运行GCC,你可以使用 -Xlinker 标志传递给链接程序的选项。在你的榜样,

If running gcc, you could use the -Xlinker flag to pass the option on to the linker. In your example,

gcc -o outfile -Xlinker --defsym -Xlinker key=0x9000 sourcefile.c

下面的程序,从而编制,输出 0×9000

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

如果你有,你想在一些内存区域变量的集合,一个更合适的方法可能是使用的输出节由尼古拉的建议,也许在用自定义 LD 脚本。

If you have a collection of variables you want to be in some region of memory, a more appropriate method might be to use output sections as suggested by Nikolai, perhaps in conjunction with a custom ld script.

这篇关于在具体地址外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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