c++ - 是否有任何工具/方法可以从 C++ 代码中检测/删除所有未使用的变量、宏、 header (包含)和函数?

标签 c++ code-cleanup devtools

我必须定制一些为其他目的而编写的项目,但一些核心功能对于我的项目是相同的并且可以正常工作。但是有很多变量、宏、函数等。它们对我当前的上下文没有用,它们只会使代码非常难以阅读并且不必要地大。

所以我开始通过在 Netbeans 中使用“查找引用”和“显示调用图”来删除变量宏函数等。我正在为 c/c++ 使用 netbeans 远程开发工具。 但它很麻烦。那么有什么工具可以清理吗?

最佳答案

据我所知,目前没有工具可以完成您提到的所有事情,但是有一个工具可以帮助清理未使用的包含 header :include-what-you-use

"Include what you use" means this: for every symbol (type, function variable, or macro) that you use in foo.cc, either foo.cc or foo.h should #include a .h file that exports the declaration of that symbol. The include-what-you-use tool is a program that can be built with the clang libraries in order to analyze #includes of source files to find include-what-you-use violations, and suggest fixes for them.

The main goal of include-what-you-use is to remove superfluous #includes. It does this both by figuring out what #includes are not actually needed for this file (for both .cc and .h files), and replacing #includes with forward-declares when possible.

人们可能会期望 Clang static analyzer会这样做,但据我所见the availalbe checks不要提供这样的东西。

这可能是某人联系 suggest a feature request 的好时机到分析仪或使用 LibTooling 创建一个单独的工具与 Clang Tools 中描述的工具类似

同时,我建议您启用 -Wall-Wextra 编译器标志,这将触发以下警告(以及其他警告)(请参阅 GCC 文档下面):

  • -Wunused-function
  • -Wunused-label
  • -Wunused-value
  • -Wunused-变量
  • -Wunused-参数
  • -Wunused-but-set-parameter

如果由于某种原因你不想这样做,你可以添加 -Wunused 它将仅启用上述 -Wunused 选项的组合,而没有 -Wall 或 -Wextra 的其他标志补充。

But in order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter.

当然,这意味着您必须手动进行清理

如果你想更加迂腐,不妨通过添加 -pedantic-errors 标志将所有警告转换为错误

更多详情请阅读GCC Warnings Options documentation .

关于c++ - 是否有任何工具/方法可以从 C++ 代码中检测/删除所有未使用的变量、宏、 header (包含)和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538479/

相关文章:

C++ 因式分解模板方法专门化模板类,这可能吗?

c++ - 我可以在 C++11 中使用键和值都是枚举类的 std::map 吗?

java - Java重构练习

rx-java - RxJava Conditional FlatMap Cleaner Way

sql - 如何编写干净的 SQL Server 存储过程

将包文档渲染到 github wiki

c++ - 如何将OpenCl库链接到Clion IDE

c++ - 将返回表达式隐式转换为 bool

r - 错误 : unable to collate and parse R files for package - upload to CRAN

javascript - Firefox 的 monitorEvents() 等价物是什么?