public
Last active

Demo of macro usage for code generation

  • Download Gist
test.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <stdio.h>
 
/* ----------------------------------------------------------------------
This part declare all structs from the "the-structs.def" file
*/
 
#define STRUCT_BEGIN(_name) struct _name {
#define STRUCT_END(_name) };
#define STRUCT_FIELD(_type, _name) _type _name;
 
#include "the-structs.def"
 
// then undef them
#undef STRUCT_BEGIN
#undef STRUCT_END
#undef STRUCT_FIELD
 
/* ----------------------------------------------------------------------
This part implements print functions for all structs in "the-structs.def" file
*/
 
#define STRUCT_BEGIN(_name) void print_ ## _name(struct _name *s) {
#define STRUCT_END(_name) }
#define STRUCT_FIELD(_type, _name) printf("%s = " STRUCT_##_type##_str "\n", #_name, s->_name);
#define STRUCT_int_str "%d" /* this is to output an int */
// add more types...
 
#include "the-structs.def"
 
// then undef them
#undef STRUCT_BEGIN
#undef STRUCT_END
#undef STRUCT_FIELD
#undef STRUCT_int_str
 
/* ----------------------------------------------------------------------
Lets put it to use
*/
 
int main() {
struct s_my_struct s;
 
s.fieldName1 = 1;
s.fieldName2 = 2;
s.fieldName3 = 3;
 
print_s_my_struct(&s);
 
return 0;
}
the-structs.def
1 2 3 4 5 6 7 8 9
STRUCT_BEGIN(s_my_struct)
STRUCT_FIELD(int, fieldName1)
STRUCT_FIELD(int, fieldName2)
STRUCT_FIELD(int, fieldName3)
STRUCT_END(s_my_struct)
 
/* Note that you can add more structs here and
all will automatically get defined and
get the print function implemented */

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.