Search code examples
ceclipseinitializationembeddedflash-memory

How to initialize structure in flash at compile time?


I'm working on an embedded C project and would like to initialize, at compile-time, a structure that is stored in flash (0x1200u), but I keep getting weird compile errors.

typedef struct {
    float foo[2];
    ...other stuff...
} MY_STRUCT_DATA_TYPE

#define MY_FLASH_STRUCT    ((MY_STRUCT_DATA_TYPE *)(0x1200u)) // <-- error here

MY_FLASH_STRUCT MY_InitdStruct = {
        .foo[0] =  0.12345f;
        .foo[1] =  0.54321f;
        ...other stuff...
};

The error I'm getting is "expected '{' before '(' token." Anyone know how to make this work?

Update

Added to linker file...

MEMORY
{
  ... other stuff ...
  m_my_data_section    (RW)  : ORIGIN = 0x00001200, LENGTH = 0x00000400
  ... other stuff ...
}

SECTIONS
{
  ... other stuff ..
  .my_data_section :
  {
    . = ALIGN(4);
    KEEP(*(.my_data_section))
    . = ALIGN(4);
  } > m_my_data_section
  ... other stuff ...
}

C code...

static volatile const MY_STRUCT_DATA_TYPE __attribute__ ((section (".my_data_section"))) MY_InitdStruct = {
        .foo[0] =  0.12345f;
        .foo[1] =  0.54321f;
        ...other stuff...
};

I'm not sure the static or const keywords are necessary, since it's intended only for one-time use to initialize that section of flash memory at compile-time, but it doesn't hurt to restrict the label's usage.


Solution

  • That makes no sense at all, syntactically that is.

    What you need to do is figure out how your compiler supports this, since it's not something you can do with just standard C.

    With GCC, you use __attribute() to put the symbol in a particular segment, then use the linker script to put that segment in a particular piece of actual memory.

    Or, just give your compiler the benefit of the doubt and try a static const structure, that should end up in flash.