以编程方式解析和编辑 C++ 源文件 [英] Programmatically parse and edit C++ Source Files

查看:53
本文介绍了以编程方式解析和编辑 C++ 源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式解析和编辑 C++ 源文件.我需要在代码的某些部分(即在函数、类块等中)更改/添加代码.我也(最好)也能得到评论.

I want to programmatically parse and edit C++ source files. I need to change/add code in certain sections of code (i.e. in functions, class blocks, etc). I would also (preferably) be able to get comments as well.

我想做的部分可以用下面的一段代码来解释:

Part of what I want to do can be explained by the following piece of code:

CPlusPlusSourceParser cp = new CPlusPlusSourceParser("x.cpp");  // Create C++ Source Parser Object
CPlusPlusSourceFunction[] funcs = cp.getFunctions();  // Get all the functions

for (int i = 0; i &lt funcs.length; i++) {  // Loop through all functions
    funcs[i].append(/* … code I want to append …*/);  // Append some code to function 
}
cp.save(); // Save new source
cp.close(); // Close file

我该怎么做?

我希望能够最好使用 Java、C++、Perl、Python 或 C# 执行此操作.但是,我对其他语言的 API 持开放态度.

I’d like to be able to do this preferably in Java, C++, Perl, Python or C#. However, I am open to other language API’s.

推荐答案

这类似于 AST from C代码

如果您熟悉 Java,antlr 可以轻松地将您的代码解析为抽象语法树,然后对该树应用转换.默认的 AST 转换是简单地打印出原始源.

If your comfortable with Java antlr can easily parser your code into an abstract syntax tree, and then apply transformation to that tree. A default AST transform is to simply print out the original source.

这篇关于以编程方式解析和编辑 C++ 源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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