如何将变量放置在内存中的给定绝对地址(使用 GCC) [英] How to place a variable at a given absolute address in memory (with GCC)
问题描述
RealView ARM C 编译器支持将变量放置在给定的内存地址使用变量属性 at(address)
:
The RealView ARM C Compiler supports placing a variable at a given memory address using the variable attribute at(address)
:
int var __attribute__((at(0x40001000)));
var = 4; // changes the memory located at 0x40001000
GCC 有类似的变量属性吗?
Does GCC have a similar variable attribute?
推荐答案
我不知道,但您可以轻松地创建这样的解决方法:
I don't know, but you can easily create a workaround like this:
int *var = (int*)0x40001000;
*var = 4;
这不是完全相同的东西,但在大多数情况下是完美的替代品.它适用于任何编译器,而不仅仅是 GCC.
It's not exactly the same thing, but in most situations a perfect substitute. It will work with any compiler, not just GCC.
如果您使用 GCC,我假设您也使用 GNU ld(当然,虽然不确定)并且 ld 支持将变量放置在 wherever你想要他们.
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.
我想让链接器完成这项工作很常见.
I imagine letting the linker do that job is pretty common.
受@rib 回答的启发,我将补充一点,如果绝对地址用于某个控制寄存器,我会在指针定义中添加 volatile
.如果只是内存,没关系.
Inspired by answer by @rib, I'll add that if the absolute address is for some control register, I'd add volatile
to the pointer definition. If it is just RAM, it doesn't matter.
这篇关于如何将变量放置在内存中的给定绝对地址(使用 GCC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!