Difference between revisions of "How to place variables in Flash"

From SEGGER Wiki
Jump to: navigation, search
(Created page with "Variables are usually placed in RAM and constant data is placed in Flash. However, there are some special situations where data in Flash is modified (i.e. making it a variabl...")
 
(One intermediate revision by one other user not shown)
Line 13: Line 13:
 
<source lang="c">
 
<source lang="c">
 
const unsigned int ValidMarker = 0xA5A5A5A5;
 
const unsigned int ValidMarker = 0xA5A5A5A5;
const unsigned int FW_Valid; values
+
const unsigned int FW_Valid;
   
 
int CheckFirmware() {
 
int CheckFirmware() {
Line 55: Line 55:
 
keep { symbol FW_Valid };
 
keep { symbol FW_Valid };
 
</pre>
 
</pre>
  +
  +
[[Category:Embedded Studio]]

Revision as of 10:02, 14 March 2023

Variables are usually placed in RAM and constant data is placed in Flash.

However, there are some special situations where data in Flash is modified (i.e. making it a variable) and the code needs to work on the possibly modified data.

This article describes how to place such a symbol using the SEGGER linker.

Requirements

  • Embedded Studio v6.34a or later

Example Situation

The following code will be executed by a bootloader.

const unsigned int ValidMarker = 0xA5A5A5A5;
const unsigned int FW_Valid;

int CheckFirmware() {
  if (FW_Valid == ValidMarker) {
    return 1;
  } else {
   return 0;
  }
}

However, this implementation brings a potential problem with it.

Variable FW_Valid could be removed by optimization, because we comparing two constant.

A solution for that is to tell the compiler that the variable is changed outside of the application (volatile).

volatile const unsigned int FW_Valid;

But volatile and const cannot be used together (const overrides volatile).

So we have to create a normal volatile variable:

volatile unsigned int FW_Valid;

The next Issue is that the created Variable is now placed in RAM. However we can place the variable explicitly in Flash with a linker script:

place in FLASH { symbol FW_Valid };

Now the variable also might be removed by optimization, because it is not directly written anywhere.

So we have to tell the linker to keep the variable:

keep { symbol FW_Valid };