This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Need to change the default alignment of a data type


Hi Pete,

> I am working on a project porting C code from AIX (xlC 7.0) to Linux (gcc 4.1.1) where the code will continue run on both platforms so there needs to be consistency with the size and alignment of various structs that get passed around.

How are you passing the structs around?

If you are communicating data between AIX and Linux through a socket or through a file, you should be reading/writing a canonical format rather than reading/writing the struct (which may have pad bytes, or different endian-ness).

For example:

Let's assume that on AIX an int is 32-bit, and on Linux the int is 64-bit because you are running a 64-bits per word platform.  Also, AIX is little-endian and Linux is big-endian.

Also, let's assume that on AIX the double is more-or-less little-endian 64-bit IEC 60559 (aka IEEE 754), and on Linux is more-or-less big-endian 64-bit IEC 60559.

struct Message
{
  int header; // Even though 64-bit on Linux, should not exceed 32-bit range.
  double value;
};

I would package the Message up this way:

typedef char byte;
struct MessageRecord
{
  byte header[4]; // 32-bit signed int, big-endian
  byte value[8]; // 64-bit double (IEC 60559), big-endian
};

struct MessageRecord PackMessage(struct Message);
struct Message UnpackMessageRecord(struct MessageRecord);

Then you'd only read/write or fread/fwrite the MessageRecord to your fd or FILE*.

The #include <arpa/inet.h> has htons and htonl routines are useful to convert 16-bit and 32-bit from host-endian to network-endian (big-endian).  Also, ntohs and ntohl to convert the other way.  I'm not sure if there is a prefab 64-bit htonq and ntohq.

I presume the routine for PackMessage and UnpackMessageRecord are easy enough to implement.

Something like XML (e.g., SOAP) is also a good transport format, but has some parsing overhead and often a larger footprint.  Or JSON.  Or Lua-code-as-a-transport-format.

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]