Global and static variables are zero-initialized by default. 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.
Variables can be declared as noinit or persistent using either pragmas or variable attributes. See Section 5.17.3 for information about using variable attributes in declarations.
Noinit and persistent variables behave identically with the exception of whether or not they are initialized at load time.
By default, noinit or persistent variables are placed in sections named .TI.noinit and .TI.persistent, respectively. The location of these sections is controlled by the linker command file. Typically .TI.persistent sections are placed in FRAM for devices that support FRAM and .TI.noinit sections are placed in RAM.
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; |