Search code examples
cmakefile

mapping a C struct on memory


I have to place a structure in a precise position in the memory and I have to find the solution using the linker. (We are talking about C code for embedded systems)

the structure is declared as follows:

config.c

const conf_t gv_confReg;

config.h

typedef struct
{
    int val1;
    int val2;
} conf_t;

extern const conf_t gv_confReg;

I wrote on Makefile:

...
CFLAGS= -g -DDEBUG=$(DEBUG) -I $(INC) -Xlinker -Map=$(OBJ)/out.map -T linker.ld
...
$(OBJ)/config.o: $(SRC)/config.c $(INC)/conf.h
        $(CC) $(CFLAGS) -o $@ -c $<

I wrote on linker.ld:

MEMORY 
{
    PROM (r) : ORIGIN = 0x40000000, LENGTH = 256k
}

SECTIONS 
{
    . = ORIGIN(PROM);
    .data : {
        *(.data)
        } > PROM : ADDR = 0x40000000
        
        
    .init_array : {
        PROVIDE(__init_array_start = .);
        KEEP(*(.init_array))
        PROVIDE(__init_array_end = .);
    }
}

however when I go to examine the addresses, I find that gv_confReg is not at the address 0x40000000. where am I wrong? Thank you


Solution

  • To have the struct initialized at that specific address, a memory area must be created specifically for it. E.g. as follows (adjust the size as needed):

    MEMORY 
    {
        CONF (r) : ORIGIN = 0x40000000, LENGTH = 256
        PROM (r) : ORIGIN = 0x40000100, LENGTH = 256k-256
    }
    ...
      .conf :
      {
        KEEP (*(.conf*));
      } >CONF
    
    

    Then tell the compiler to create the struct in that area. The notation is compiler-specific. For GCC:

    __attribute__((section(".conf"))) const conf_t gv_confReg = {1, 2};