5

Is there a way to design a macro that could ensure an element is at the start of a struct during it's definition? For example:

typedef struct {
  START(int a);
} b;
// Becomes
typedef struct {
  int a;
} b;

But generate a compiletime error when it isn't the first element?

typedef struct {
  int c;
  START(int a);
} b;
// Generate an error

I was thinking you could use a combo of the OFFSETOF and BUILD_BUG_ON_ZERO macros but this would require knowing the struct layout while initializing it, and produces an error because the variable is undeclared.

Is this possible in C?

J V
  • 11,402
  • 10
  • 52
  • 72
  • 6
    If you want it at the start then why not just put it at the start? – Sean Jul 02 '14 at 15:03
  • @sean I want to refer to the first element and the struct containing it by the same pointer (A cheap 'n nasty single inheritance implementation) so if any of the structs are off by a single char the whole thing will fall apart - I want a compile-time guarantee that it's in the right place. Just curious if it can be done – J V Jul 02 '14 at 15:07
  • You might want to read about [`offsetof`](http://en.cppreference.com/w/cpp/types/offsetof). Though there will be a problem because when you use the `START` macro the type-alias `b` will not exist, and the structure is not fully defined so using the `offsetof` macro might not be reliable. – Some programmer dude Jul 02 '14 at 15:09
  • `offsetof` is required to be a compile-time constant in C, so you can just do a compile-time assert that `offsetof(struct foo, a) == 0`. – M.M Jul 05 '14 at 05:07

2 Answers2

4

Use a compile time assertion at the locations you actually assume that layout, instead of at the definition site. Of course you will need to actually define it at the start in order to pass the assertion.

Community
  • 1
  • 1
Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49
  • I'd have to build it into a constructor macro, but this does seem to be the only way to do it – J V Jul 05 '14 at 09:57
1

Perhaps something like this would work for you:

#define typedef_header(x) typedef struct { x

typedef_header(int a);
  int c;
} b;

int main()
{
  b x;
}
Martin G
  • 17,357
  • 9
  • 82
  • 98