See also typedef, struct union.
Example struct that will be used multiple times
//Defining a struct called MY_SPECIAL_STRUCT
struct MY_SPECIAL_STRUCT
{
uint8_t MyU8Variable1;
uint8_t MyU8Variable2;
uint32_t MyU32Variable1;
uint32_t MyU32Variable1;
uint8_t Spare[20];
};
struct MY_SPECIAL_STRUCT MySpecialStruct1;
struct MY_SPECIAL_STRUCT MySpecialStruct2;
//Using it:
// MySpecialStruct1.MyU8Variable2 = 69;
//If you need to define them elsewhere as extern:
extern struct MY_SPECIAL_STRUCT MySpecialStruct1;
extern struct MY_SPECIAL_STRUCT MySpecialStruct2;
Example struct for use as one object
//Defining a struct that will be used as MySpecialStruct
struct MY_SPECIAL_STRUCT
{
uint8_t MyU8Variable1;
uint8_t MyU8Variable2;
uint32_t MyU32Variable1;
uint32_t MyU32Variable1;
uint8_t Spare[20];
} MySpecialStruct;
//Using it:
// MySpecialStruct.MyU8Variable2 = 69;
//If you need to define it elsewhere as extern:
extern struct MY_SPECIAL_STRUCT
{
uint8_t MyU8Variable1;
uint8_t MyU8Variable2;
uint32_t MyU32Variable1;
uint32_t MyU32Variable1;
uint8_t Spare[20];
} MySpecialStruct;
Checking a struct size
On 16bit and 32bit platforms your struct may end up being bigger in memory that the sum of its individual variables due to padding bytes. This can be a useful check when you are byte copying it for instance to eeprom memory and back.
#define EXT_EEPROM_NV_MEMORY_LEN 30
struct NON_VOLATILE_STRUCT
{
uint8_t MyU8Variable1;
uint8_t MyU8Variable2;
uint32_t MyU32Variable1;
uint32_t MyU32Variable1;
uint8_t Spare[20];
} NonVolatile;
//----- CHECK FOR NV MEMORY SIZE ISSUE -----
if (sizeof(NonVolatile) > EXT_EEPROM_NV_MEMORY_LEN)
printf("WARNING - NonVolatile is larger than EXT_EEPROM_NV_MEMORY_LEN - not all bytes being stored! (NonVolatile is using %i bytes)\n", sizeof(NonVolatile)); //This is OK, as long as the end of NonVolatile is unused
if (sizeof(NonVolatile) < EXT_EEPROM_NV_MEMORY_LEN)
{
printf("CRITICAL ERROR - EXT_EEPROM_NV_MEMORY_LEN NOT BIG ENOUGH! (Change to %i bytes)\n", sizeof(NonVolatile)); //This is not OK as ExtEepromRead() will be writing to memory locations after NonVolatile
while (1)
; //<<<Die here
}
