在特定地址的外部变量 [英] Extern variable at specific address

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

问题描述

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

  int key __attribute __((__ at(0x9000))); 

AFAIK此特定选项仅适用于嵌入式系统。

解决方案

轻松选项:



定义

  int * const key = int *)0x9000; 

并在其他地方引用 *键



全部 externs有特定的地址!这些地址可能在链接时间之前是未知的,但它们必须最终解决。如果你声明 extern int key; ,那么你必须在链接时为符号 key 提供一个地址。这可以使用链接器脚本完成(请参见使用ld )或在链接器命令行使用 -defsym 选项。



gcc,可以使用 -Xlinker 标志将选项传递给链接器。在您的示例中,

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

以下程序由此编译,输出 0x9000

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

如果你有一个变量集合, ,一个更合适的方法可能是使用由Nikolai建议的输出节,也许结合自定义的 ld 脚本。


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

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

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?

解决方案

Easy option:

Define

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

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

Pointerless option:

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.

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

The following program, thus compiled, outputs 0x9000.

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

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天全站免登陆