C语言 如何将变量放置在内存中的给定绝对地址处(使用 GCC)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4067811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to place a variable at a given absolute address in memory (with GCC)
提问by Bas van Dijk
The RealView ARM C Compiler supportsplacing a variable at a given memory address using the variable attribute at(address):
RealView ARM C 编译器支持使用变量属性将变量放置在给定的内存地址at(address):
int var __attribute__((at(0x40001000)));
var = 4; // changes the memory located at 0x40001000
Does GCC have a similar variable attribute?
GCC 是否有类似的变量属性?
采纳答案by Prof. Falken contract breached
I don't know, but you can easily create a workaround like this:
我不知道,但您可以轻松创建这样的解决方法:
int *var = (int*)0x40001000;
*var = 4;
It's not exactlythe same thing, but in most situations a perfect substitute. It will work with any compiler, not just GCC.
这并不完全相同,但在大多数情况下是完美的替代品。它适用于任何编译器,而不仅仅是 GCC。
If you use GCC, I assume you also use GNU ld(although it is not a certainty, of course) and ld has support for placing variables wherever you want them.
如果您使用 GCC,我假设您也使用GNU ld(当然,虽然不确定)并且 ld 支持将变量放置在您想要的任何位置。
I imagine letting the linker do that job is pretty common.
我想让链接器完成这项工作是很常见的。
Inspired by answer by @rib, I'll add that if the absolute address is for some control register, I'd add volatileto the pointer definition. If it is just RAM, it doesn't matter.
受到@rib 的回答的启发,我会补充一点,如果绝对地址用于某个控制寄存器,我会添加volatile到指针定义中。如果它只是RAM,那没关系。
回答by Thomas M. DuBuisson
You could use the section attributesand an ld linker scriptto define the desired address for that section. This is probably messier than your alternatives, but it is an option.
回答by rib
You answered your question, In your link above it states:
您回答了您的问题,在您上面的链接中指出:
With the GNU GCC Compiler you may use only pointer definitions to access absolute memory locations. For example:
使用 GNU GCC 编译器,您只能使用指针定义来访问绝对内存位置。例如:
#define IOPIN0 (*((volatile unsigned long *) 0xE0028000))
IOPIN0 = 0x4;
Btw http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Variable-Attributes.html#Variable%20Attributes
顺便说一句http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Variable-Attributes.html#Variable%20Attributes
回答by user6409471
extern const uint8_t dev_serial[12];
asm(".equ dev_serial, 0x1FFFF7E8");
/* or asm("dev_serial = 0x1FFFF7E8"); */
...
for (i = 0 ; i < sizeof(dev_serial); i++)
printf((char *)"%02x ", dev_serial[i]);

