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
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.