如何自动生成C代码

0xh*_*ker 5 c code-generation

我正在做一个 C 项目。我观察到很多代码可以根据某些规则自动生成。IE。如果我只指定C结构,基于此,代码可以自动生成。我知道可以做到,但我以前没做过。如果经验丰富的 C 程序员能够提供某些指导或分享他们关于如何以最少的工程工作完成此类事情的经验,那就太好了。

编辑:具体来说,我是否需要用 C 编写一个自定义解析器来完成所有这些操作,或者是否有一些更简单的方法来处理这个问题?

epa*_*tel 2

我见过的一种有效方法是使用宏(一种经常令人讨厌的工具)。宏有两个功能可以帮助让生活变得更轻松,单个散列“#”可以将参数转换为字符串,即将#_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 
Run Code Online (Sandbox Code Playgroud)

然后,我们可以在想要声明或实现应该处理该结构的内容的地方以不同的方式定义宏。IE

#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
Run Code Online (Sandbox Code Playgroud)

并创建一个打印结构的函数

#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
Run Code Online (Sandbox Code Playgroud)

其他用途可以是自动生成函数,即交换字节等。

在这里做了一个小例子作为要点https://gist.github.com/3786323