使用 gcc 扩展 c 编程语言
我想编写自己的编程语言作为c 编程语言的扩展。我正在发明的整个编程语言只是转换为有效的 C 代码的简写。例如:
namespace TcpConnection {
void* connect(char *addr)
}
将翻译为:
void* TcpConnection_connect(char *addr)
所做的只是简单的名称替换。这只是我想提供的扩展的一个示例。另一个简单的扩展是函数重载(这会将其参数的类型连接到函数名称的末尾。
无论如何,结果都是完全有效的 C 代码。有没有办法在不进入 gcc 代码的情况下做到这一点?
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:
namespace TcpConnection {
void* connect(char *addr)
}
would translate to:
void* TcpConnection_connect(char *addr)
All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.
In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以编写一个预处理器来解析您的语言并将其编译为 C,然后将其传递给 gcc。这就是 C++ 早期实现的工作原理。然而,您可能更喜欢破解 LLVM 的 clang,它旨在支持多种 C 系列语言,并且作为 LLVM 的一部分,还被设计为更加模块化且更易于扩展。
You could write a preprocessor that parses your language and compiles it to C, which is then passed on to gcc. This is how early implementations of C++ worked. However, you may prefer to hack on LLVM's clang, which is designed to support several C-family languages and, as part of LLVM, is also designed to be more modular and easier to extend.
对于原型设计,也许只需使用用您选择的语言(C、Perl、Python...)编写的预处理器,然后将其构建到您的 Makefile 规则中。只是为了获得一种简单、低成本的方法来尝试一切...
使用不同的文件扩展名,并将 .foo 转换为 .c。
For prototyping, maybe just go with a preprocessor written in the language of your choice (C, Perl, Python...) and then build it into your Makefile rules. Just to get an easy, low-cost way to try it all out...
Use a different file extension, and turn .foo into .c.
我使用一些 C99 宏魔法和 Perl 做了类似的事情,为自定义字节码格式嵌入汇编语言。
宏
转换
为
通过 Perl 脚本进行管道传输以获取
gcc 和 perl 的示例调用如下所示:
它比严格必要的更复杂,但我发现 C 预处理器在我的自定义预处理器之前运行是有益的,而且我也喜欢通过使用编译指示,源保持合法 C.
I did something similar to embed an assembly language for a custom bytecode format, using some C99 macro magic and Perl.
The macros
transform
into
which gets piped through a Perl script to get
A sample invocation of gcc and perl would look like this:
It's more complicated than stricly necessary, but I found it beneficial that the C preprocessor runs before my custom preprocessor, and I also liked that by using pragmas, the source stays legal C.
你可以在 http://cil.sourceforge.net/ 之上破解一些东西
Clang 是另一种选择,但它是不是最有用的代码重写工具,并且修改其解析器前端并不那么容易。
You could hack something on top of http://cil.sourceforge.net/
Clang is another option, but it's not the most useful code rewriting tool, and modifying its parser frontend is not that easy.