The NOINIT and PERSISTENT Pragmas

Global and static variables are zero-initialized. However, in applications that use non-volatile memory, it may be desirable to have variables that are not initialized. Noinit variables are global or static variables that are not zero-initialized at startup or reset.

Persistent and noinit variables behave identically with the exception of whether or not they are initialized at load time.

The NOINIT pragma may be used in conjunction with the LOCATION pragma to map variables to special memory locations, like memory-mapped registers, without generating unwanted writes. The NOINIT pragma may only be used with uninitialized variables.

The PERSISTENT pragma is similar to the NOINIT pragma, except that it may only be used with statically-initialized variables. Persistent variables disable startup initialization; they are given an initial value when the code is loaded, but are never again initialized.

NOTE

When using these pragmas in non-volatile FRAM memory, the memory region could be protected against unintended writes through the device's Memory Protection Unit. Some devices have memory protection enabled by default. Please see the information about memory protection in the datasheet for your device. If the Memory Protection Unit is enabled, it first needs to be disabled before modifying the variables.

If you are using non-volatile RAM, you can define a persistent variable with an initial value of zero loaded into RAM. The program can increment that variable over time as a counter, and that count will not disappear if the device loses power and restarts, because the memory is non-volatile and the boot routines do not initialize it back to zero. For example:

#pragma PERSISTENT(x) #pragma location = 0xC200 // memory address in RAM int x = 0; void main() { run_init(); while (1) { run_actions(x); __delay_cycles(1000000); x++; } }

The syntax of the pragmas in C is:

#pragma NOINIT (x)
intx;
#pragma PERSISTENT (x)
intx=10;

The syntax of the pragmas in C++ is:

#pragma NOINIT
intx;
#pragma PERSISTENT
intx=10;

The syntax of the GCC attributes is:

intx__attribute__((noinit));
intx __attribute__((persistent)) = 0;