Read-only Objects in RAM

Last modified by Microchip on 2024/01/29 20:38

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 behavior 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 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 from 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 initialized 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.