Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place a variable at a given absolute address in memory (with GCC)

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 

Does GCC have a similar variable attribute?

like image 962
Bas van Dijk Avatar asked Nov 01 '10 09:11

Bas van Dijk


People also ask

What is __ attribute __ in C?

The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.


1 Answers

I don't know, but you can easily create a workaround like this:

int *var = (int*)0x40001000; *var = 4; 

It's not exactly the same thing, but in most situations a perfect substitute. It will work with any compiler, not just 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.

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 volatile to the pointer definition. If it is just RAM, it doesn't matter.

like image 185
Prof. Falken Avatar answered Sep 19 '22 13:09

Prof. Falken