Charlie Sale
Charlie Sale

Reputation: 185

Create a struct in C Preprocessor

Right now, I am writing a small project in C to test out some serialization techniques. One way that I am doing this is through the use of unions. Something that I would like to try is creating a union in the C preprocessor that holds a user-defined structure. For example, something like this:

#define create_union(name_of_structure, type_of_structure) \ 
                                                           \
typedef union name_of_structure {                          \                                 
      typeof(type_of_structure) structure;                 \                        
      char buffer_that_holds_structure[sizeof(type_of_structure)]; \
} name_of_structure;

/* Usage */
struct my_data {
      int id;
      int other_value;
};

create_union(my_data_t, struct my_data);
/* Data type my_data_t (union my_data_t) now exists */

First of all, is this feasible? If it is, how would I go about doing this? If not, is there an alternative method I can use?

Thanks!

Upvotes: 1

Views: 2765

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263647

Yes, it's possible, and your code is very close to correct.

I'd drop the semicolon at the end of the macro definition. I'd also drop the use of typeof; it's not portable and it's not needed unless you want to use an expression, rather than a type name, as the first argument to create_union.

Here's how I'd probably define it. (I don't bother with typedefs for struct or union types; I just use the name struct foo or union foo unless the type is intended to be completely opaque. Feel free to use the typedef if you prefer.) (I've also used unsigned char rather than char, since that's how object representations are defined.)

#define CREATE_UNION(new_type, existing_type) \
union new_type {                              \
      existing_type obj;                      \
      unsigned char rep[sizeof(existing_type)]; \
}

And you can then do:

CREATE_UNION(int_wrapper, int);
int_wrapper foo;

Note that what you're defining is a union, not a structure.

Upvotes: 2

Related Questions