如何以编程方式更改 C++ 中的源代码文件?
我需要一种方法来获取 C/C++ 源代码文件,检查并对其执行一些修改,然后将修改后的变体写回磁盘。我可能的用例是:
- 突变测试,例如故意破坏计算以检查测试是否可以捕获它。
- 改变可见性范围或注释函数和方法。为了将一个大文件分割成几个较小的文件,但仍然能够将它们链接在一起,我想将一些
static
函数转换为external
函数,以便链接器可以找到他们稍后。 - 生成现有函数方法的模拟实现。对于所有外部可见的函数,创建一个具有相同原型但具有空/虚拟主体的函数,以便其他代码可以链接到它。
此类工作流程是否有现有的解决方案?
我最感兴趣的是处理函数/方法。文件中包含的其余信息(例如包含、类型定义等)对我来说不太重要,但它们必须保留在输出中,以便最终结果在语法上保持正确。
应用一堆正则表达式来提取/修改文本的简单方法是可能的。但它显然无论如何都不可靠。我想避免编写一个成熟的 C++ 解析器。即使拥有这样的解析器也不能解决将修改后的解析树保存回文件的后续任务。
I need a way to take a C/C++ source code file, inspect and perform some modifications to it, and then write the modified variant back to disk. Possible use cases that I have for it are:
- Mutation testing, such as intentionally corrupting calculation in order to check if tests can catch it.
- Altering visibility scope or annotating functions and methods. In order to split a large file into several smaller files but still being able to link them together, I want to turn some
static
functions intoexternal
functions so that the linker can find them later. - Generation of mock implementations of existing functions methods. For all externally visible functions, create a function with identical prototype but with empty/dummy body so that other code can link against it.
Are there existing solutions for such workflow?
I am mostly interested in dealing with functions/methods. The rest of information contained in a file, such as includes, type definitions etc. are less important for me, but they must be preserved in the output so that the end result remains syntactically correct.
A straightforward approach of applying a bunch of regular expressions to extract/modify the text is possible. But it is obviously not reliable in a any way. I would like to avoid writing a full-blown C++ parser. Even having such a parser does not solve the follow-up task of saving the modified parse tree back to a file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LibTooling 和 libclang 通常用于开发此类重构工具(clang 格式,clang-tidy 等)。
LibTooling and libclang are commonly used to develop such refactoring tools (clang-format, clang-tidy, etc.).