Read-only Objects in RAM

It is possible to place read-only objects in RAM using a simple coding trick with the MPLAB® XC8 compiler.

The compiler ordinarily places objects in either data or program memory. Regular objects are located in data memory (RAM), but objects that are defined using the const specifier are considered read-only and might be placed in program memory since they cannot be modified. This behaviour is reasonable, since it preserves more of the device’s precious RAM, but the code to read objects in program memory is typically more complex than that for objects in RAM, resulting in slower program execution and a larger code size.

If you have unused device RAM, there is a way to move const-qualified objects into this memory, such that their read-only status is preserved, but that they are accessed faster. To do this, place the objects in a structure, either by themselves or with other objects. Qualify all the members that are to be read-only with the const specifier. For example, in the following definition:

struct {
  int input;
  const int scale;
} myStruct = { 0x0, 0x1234 };

the object myStruct.input will be placed in RAM and be readable and writable; the object myStruct.scale will be placed in RAM but will be read-only, so you cannot modify it. Note that qualifying structure members is different to qualifying the structure as a whole, so in the following example:

const struct {
  int scale;
} myStruct = { 0x1234 };

the object myStruct.scale will be read-only but will reside in program memory.

Note that const-qualified objects in RAM will take longer to be initialised by the runtime startup code, but this occurs only once, whereas these objects might be more efficiently accessed many times in the program. Also note that all const auto and parameter variables are always placed in RAM, so this trick does not need to be used for those objects.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.