如何自动生成C代码 [英] How to generate C code automatically

查看:533
本文介绍了如何自动生成C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C进行项目。我观察到可以根据某些规则自动生成很多代码。即。如果仅指定C结构,则可以基于该结构自动生成代码。我知道可以做到,但是我以前没有做过。如果经验丰富的C程序员可以给出某些指示或以最少的工程工作量分享如何做这些事情的经验,那就太好了。

I am working on a project in C. I observe that a lot of code can be automatically generated based on certain rules. ie. if I specify just C structures, based on that, the code can be automatically generated. I know it can be done, but I havent done it before. It will be nice if experienced C programmers can give certain pointers or share their experience on how to do such things with minimum engineering effort.

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

To be very specific, do I need to write a custom parser in C to do all that or is there some easier way to deal with this?

推荐答案

最困难的部分是做比1:1语法替换更有意义的事情。

The hard part is doing anything terribly meaningful beyond 1:1 syntax replacement.

如果您过于依赖宏,则会遇到认知漂移的(虚构名称)问题,此时您正在设计自己的语言(一种宏),但编译器和正在运行的程序正在使用另一个。简单的映射不会使新语言变得更加繁琐,但是由于宏只能在 text 替换级别上起作用,即使是简单的映射也会变得过于复杂。

If you rely too heavily on macros, you run into the (made up name) issue of cognitive drift, where you are now designing your own language (a macro one) but the compiler and running program is using another. Simple mappings don't make the new language more cumbersome, but even simple mappings get complex far too quickly due to macros functioning on a text only substitution level.

如果您使用的是C ++,那么更好的解决方案是使用模板。模板提供了许多与宏相同的功能,不同之处在于它们不会遭受太多的认知漂移,因为模板会替换为对类型系统的了解。

If you are using C++, then a far better solution is to use templates. Templates offer many of the same features as macros, except that they don't suffer from as much cognitive drift, because templates substitute with awareness of the type system.

类似于C的语言结构的语法和含义不断发展,您会发现,较新的语言经常尝试通过纯C解决方案修复具有 required 的重复代码。尝试学习一些接近 C的新语言,您将对减少这种代码重复的方式有所赞赏,从而可以更好地选择C的生成成果。

As the syntax and meaning of C-like language structure evolves, you find that newer languages often try to "fix" issues with the amount of repetitive code required by a pure C solution. Try learning a few new languages that are "near" C and you will get an appreciation for ways this code duplication can be reduced, leading to better choices in "generation" efforts in C.

这篇关于如何自动生成C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆