Paulson Raja L
Paulson Raja L

Reputation: 411

How to initialize a persistent variable in c

In .h file I have a persistent variable extern <Enum Datatype> __attribute__((section(".persist"))) state

In .c file I have to initialize the variable state to one of the member of enum Example: enum state = <One of the member of enum>

If I try the above method the compiler throws the warning persistent variables cannot be initialized.

Note: The persistent variable is used for a test of PRE and POST usage of a system, hence initially in the application code I want the test to start from PRE.

Upvotes: 1

Views: 423

Answers (2)

Vishnu CS
Vishnu CS

Reputation: 851

I have been referring to this link, where it clearly says the following statement.

Any object that needs to be persistent cannot be assigned an initial value when defined. A warning will be issued if you use the __persistent qualifier with an object that is assigned an initial value, and for that object, the qualifier will be ignored.

Another useful link would be this, where it says that

The persistent attribute specifies that the variable should not be initialized or cleared at startup. Persistent data is not normally initialized by the C run-time.

In summary, persistent variable should not be initialized.

There is a code snippet available in the above link, where it says how to 'safely initialize' the persistent variable. Just pasting the same here for easy reference.

#include <xc.h>

int last_mode __attribute__((persistent)); //declaring the persistent variable.

int main()
{
    if ((RCONbits.POR == 0) &&
        (RCONbits.BOR == 0)) {
      /* last_mode is valid */
   } else {
     /* initialize persistent data */
     last_mode = 0;
   }
}

Hope it helps you.

Upvotes: 1

nielsen
nielsen

Reputation: 7594

The sole purpose of marking a variable as "persistent" is to prevent the startup code initialization of the variable. Thus it makes sense that the compiler does not allow initialization of such a variable.

If the variable really needs to be persistent (i.e. the value must be preserved over different runs of the application), then its value must be set by assignment within the code.

Upvotes: 1

Related Questions