Question

I have a structure:

struct foo {
  struct {
     int a;
     int b;
     long len;
     unsigned short c;
     unsigned short d;
  };
  char payload[1024];
} bar;

I want to find out, at configure time, if I need to insert padding to make 'payload' double-aligned.

Autoconf provides AC_CHECK_SIZEOF(type) and AC_CHECK_ALIGNOF(type), but what I really need is something like AC_CHECK_OFFSETOF(type, member). If the reported offset was not double-aligned, I could introduce enough padding to make it so.

I could run a little test program that reported offsetof(struct bar, payload), but I don't want to introduce a run-time check into my build system (we cross-compile not infrequently).

Was it helpful?

Solution

Using a zero length bitfield might solve this problem without autotool tricks.

struct foo {
  struct {
     int a;
     int b;
     long len;
     unsigned short c;
     unsigned short d;
  };
  int64_t : 0; // or long long whatever integer type is sizeof(double)
  char payload[1024];
} bar;

OTHER TIPS

You can use AC_COMPUTE_INT:

AC_COMPUTE_INT([payload_offset], [offsetof(struct bar, payload)], ...)

But it would probably be easier just to use an anonymous union to force alignment:

struct foo {
  struct {
     int a;
     int b;
     long len;
     unsigned short c;
     unsigned short d;
  };
  union {
    char payload[1024];
    double dummy; /* for alignment */
  };
} bar;

If you don't want to use a union, you can compute the padding in place:

struct foo {
  struct header {
     int a;
     int b;
     long len;
     unsigned short c;
     unsigned short d;
  };
  char padding[(alignof(double) - 1) - ((sizeof(struct header)
      + alignof(double) - 1) % alignof(double))];
  char payload[1024];
} bar;

I don't really think that autoconf can tell you that, as it is a matter of the compiler who decides to add padding or not. So I would think that the only reasonable way would be to compile a program that checks if offset of the member equals to what you think it should be equal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top