如何以编程方式更改 C++ 中的源代码文件?

发布于 2025-01-17 12:34:05 字数 539 浏览 4 评论 0原文

我需要一种方法来获取 C/C++ 源代码文件,检查并对其执行一些修改,然后将修改后的变体写回磁盘。我可能的用例是:

  1. 突变测试,例如故意破坏计算以检查测试是否可以捕获它。
  2. 改变可见性范围或注释函数和方法。为了将一个大文件分割成几个较小的文件,但仍然能够将它们链接在一起,我想将一些 static 函数转换为 external 函数,以便链接器可以找到他们稍后。
  3. 生成现有函数方法的模拟实现。对于所有外部可见的函数,创建一个具有相同原型但具有空/虚拟主体的函数,以便其他代码可以链接到它。

此类工作流程是否有现有的解决方案?

我最感兴趣的是处理函数/方法。文件中包含的其余信息(例如包含、类型定义等)对我来说不太重要,但它们必须保留在输出中,以便最终结果在语法上保持正确。

应用一堆正则表达式来提取/修改文本的简单方法是可能的。但它显然无论如何都不可靠。我想避免编写一个成熟的 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:

  1. Mutation testing, such as intentionally corrupting calculation in order to check if tests can catch it.
  2. 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 into external functions so that the linker can find them later.
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

焚却相思 2025-01-24 12:34:05

LibToolinglibclang 通常用于开发此类重构工具(clang 格式clang-tidy 等)。

LibTooling and libclang are commonly used to develop such refactoring tools (clang-format, clang-tidy, etc.).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文