1

Here is what I have, and there is still a problem - the compiler doesn't recognize the "my_reg" structure type.

../Source/functions.c:609:16: error: 'my_reg' undeclared (first use in this function) ModBusIDReg = (my_reg)const_ModBusIDReg;

// define structure in flash with constants

struct
{
  const unsigned char Reg00[32];
  const unsigned char Reg01[32];
  const unsigned char Reg02[32];
  const unsigned short Reg03;
  const unsigned short Reg04;
} const_ModBusIDReg =
{
  "My String 1" ,
  "My String 2" ,
  "My String 3" ,
   0 ,
   0
};


// define structure in RAM, tag name "my_reg"

struct my_reg
{
  unsigned char Reg00[32];
  unsigned char Reg01[32];
  unsigned char Reg02[32];
  unsigned short Reg03;
  unsigned short Reg04;
} ModBusIDReg;


// This statement is located in InitSys function.
// Both of the files where the structures were
// defined are included at the top of the file 
// where InitSys function resides.
// Make a copy of const_ModBusIDReg from
// flash into ModBusIDReg in RAM.


ModBusIDReg = (my_reg)const_ModBusIDReg;

Any ideas on how to do the direct assignment ?

1 Answers1

0

A type cast like this should resolve the compiler error:

ModBusIDReg = (my_reg)const_ModBusIDReg;

Or you could use memcpy():

memcpy(&ModBusIDReg, &const_ModBusIDReg, sizeof(my_reg));

(Sidenote at using memcpy(): In some cases, memory alignment might be an issue. But I'm no c expert. Using compiler-specific attributes like packed in the case of GCC might help, when you define the struct, depending on the platform, compiler, variable types used.)

You can also copy the members of the struct individually in a custom copy function, and initialize the unused parts if there are any. This would be clean, and very clear/explicit, and similar to a copy constructor / assignment operator used in C++ (deep copies are handled properly).


edit: Since I can't add a comment above after your last edit, I add the comment here:

./Source/functions.c:609:16: error: 'my_reg' undeclared (first use in this function) ModBusIDReg = (my_reg)const_ModBusIDReg;

In C you can use typedef in your struct type declartions, in order to avoid repeating the struct keyword throughout your code (explained in detail over here or there):

typedef struct { ... } foo;
foo x;

Here an example illustrating the mentioned ideas from above:

/* gcc -Wall -o copy_test copy_test.c && ./copy_test */

#include <stdio.h>
#include <string.h>

typedef struct {
    int var;
} my_struct;

int my_copy_func(my_struct *dst, const my_struct *src)
{
    if (!dst || !src)
        return -1;
    dst->var = src->var;
    return 0;
}

int main()
{
    const my_struct a = { .var = 42 };
    my_struct b, c, d;
    c = (my_struct)a;
    memcpy(&b, &a, sizeof(b));
    my_copy_func(&d, &a);
    printf("b.var = %d\r\n", b.var);
    printf("c.var = %d\r\n", c.var);
    printf("d.var = %d\r\n", d.var);
    return 0;
}
rel
  • 764
  • 5
  • 18