我见过的一种有效方法是使用宏(一种经常被讨厌的工具)。宏有两个功能可以让生活变得更轻松,单个哈希“#”可以将参数转换为字符串,即#_name 将被转换为"fieldName1",双哈希“##”将参数与其他可以扩展新事物的东西,即STRUCT_##_type##_str将被翻译成STRUCT_int_str,这将被翻译成"%d"
首先将结构或“描述”包装在宏中,即放入自己的文件(the-struct.def)
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
然后可以在想要声明或实现应该处理结构的事物的地方以不同的方式定义宏。即
#define STRUCT_BEGIN(_name) struct _name {
#define STRUCT_END(_name) };
#define STRUCT_FIELD(_type, _name) _type _name;
#include "the-struct.def"
// then undef them
#undef STRUCT_BEGIN
#undef STRUCT_END
#undef STRUCT_FIELD
并制作一个打印结构的函数
#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-struct.def"
// then undef them
#undef STRUCT_BEGIN
#undef STRUCT_END
#undef STRUCT_FIELD
#undef STRUCT_int_str
其他用途可以是自动生成函数以交换字节等。
在这里做了一个小例子作为要点https://gist.github.com/3786323