Skip to content

@epatel /test.c
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Demo of macro usage for code generation
#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;
}
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 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.