Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C macro to ensure element is at start of struct

Tags:

c

macros

struct

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?

like image 948
J V Avatar asked Jul 02 '14 15:07

J V


2 Answers

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.

like image 126
Dwayne Towell Avatar answered Sep 21 '22 13:09

Dwayne Towell


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;
}
like image 44
Martin G Avatar answered Sep 23 '22 13:09

Martin G