Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a variable at a specific memory location?

Tags:

c

As i am relatively new to C , i have to use for one of my projects the following: i must declare some global variables which have to be stored every time the program runs at the same memory address. I did some read and i found that is i declare it "static" it will be stored at the same memory location.

But my question is: can i indicate the program where to store that variable or not. For example : int a to be stored at 0xff520000. Can this thing be done or not? i have searched here but did not found any relevant example. If their is some old post regarding this, please be so kind to share the link .

Thank you all in advance. Laurentiu

Update: I am using a 32uC

like image 829
Laurentiu Avatar asked Mar 07 '13 09:03

Laurentiu


2 Answers

according your compiler if you use XC8 Compiler. Simply you can write int x @ 0x12 ;

in this line you set x in the memory location 0x12

like image 177
karim hussen Avatar answered Oct 05 '22 04:10

karim hussen


In your IDE there will be a memory map available through some linker file. It will contain all addresses in the program. Read the MCU manual to see at which addresses there is valid memory for your purpose, then reserve some of that memory for your variable. You have to read the documentation of your specific development platform.

Next, please note that it doesn't make much sense to map variables at specific addresses unless they are either hardware registers or non-volatile variables residing in flash or EEPROM.

If the contents of such a memory location will change during execution, because it is a register, or because your program contains a bootloader/NVM programming algorithm changing NVM memory cells, then the variables must be declared as volatile. Otherwise the compiler will break your code completely upon optimization.

The particular compiler most likely has a non-standard way to allocate variables at specific addresses, such as a #pragma or sometimes the weird, non-standard @ operator. The only sensible way you can allocate a variable at a fixed location in standard C, is this:

#define MY_REGISTER (*(volatile uint8_t*)0x12345678u)

where 0x12345678 is the address where 1 byte of that is located. Once you have a macro declaration like this, you can use it as if it was a variable:

void func (void)
{
  MY_REGISTER = 1;  // write
  int var = MY_REGISTER;  // read
}

Most often you want these kind of variables to reside in the global namespace, hence the macro. But if you for some reason want the scope of the variable to be reduced, then skip the macro and access the address manually inside the code:

void func (void)
{
  *(volatile uint8_t*)0x12345678u = 1; // write
  int var = *(volatile uint8_t*)0x12345678u; // read
}
like image 26
Lundin Avatar answered Oct 05 '22 03:10

Lundin