...pack C structures [ARM]?
I have a structure containing a number of other structures. When I look at how the structure has been laid out in memory it seems to be using too much memory. For example in the following code, type c_t is 8 bytes in length and there are 3 bytes of wasted space between a and b:
typedef struct
{
unsigned char a[1];
} a_t;
typedef struct
{
unsigned char b[2];
} b_t;
typedef struct
{
a_t a;
b_t b;
} c_t;
How can I make structure c_t occupy as little memory as possible?
You can used the packed variable attribute. For example in the following code, type c_t will have a size of 3 bytes and there will be no wasted space between a and b:
typedef struct
{
unsigned char a[1];
} __attribute__ ((packed)) a_t;
typedef struct
{
unsigned char b[2];
} __attribute__ ((packed)) b_t;
typedef struct
{
a_t a;
b_t b;
} __attribute__ ((packed)) c_t;
-
I tried the __attribute__ ((packed)) method and got compile errors like
found '(', expecting ';'
and ! missing prototype
when using the MSP430 version, so am I missing an include or similar?
#pragma pack(1) ............... #pragma pack() is a commonly used pack definition method (Visual C, IAR)
-
...you apply the packed attribute to a structure (or enumeration). I use it for a number of things, e.g.
typedef struct
{
unsigned short tcpSrcPort; // network bo
unsigned short tcpDstPort; // network bo
unsigned long tcpSeqNo; // SEND data pointer, network bo
unsigned long tcpAckNo; // Next expected RECEIVE data pointer, network bo
unsigned char tcpDataOfst;
unsigned char tcpFlags;
unsigned short tcpWindow; // how much data we will accept, network bo
unsigned short tcpChecksum;
unsigned short tcpUrgent;
unsigned char tcpOptions[4];
} __attribute__((packed)) tcpHeader;
Please sign in to leave a comment.
Comments
5 comments