遗留 C/C++ 项目中的死代码检测 [英] Dead code detection in legacy C/C++ project

查看:36
本文介绍了遗留 C/C++ 项目中的死代码检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在 C/C++ 代码中进行死代码检测?我有一个相当大的代码库可以使用,至少有 10-15% 是死代码.是否有任何基于 Unix 的工具来识别这些区域?有些代码仍然使用大量的预处理器,自动化流程可以处理吗?

How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?

推荐答案

您可以为此使用代码覆盖率分析工具并查找代码中未使用的点.

You could use a code coverage analysis tool for this and look for unused spots in your code.

gcc 工具链的一个流行工具是 gcov,以及图形前端 lcov (http://ltp.sourceforge.net/coverage/lcov.php).

A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (http://ltp.sourceforge.net/coverage/lcov.php).

如果您使用 gcc,则可以使用 gcov 支持进行编译,该支持由 '--coverage' 标志启用.接下来,使用此启用 gcov 的构建运行您的应用程序或运行您的测试套件.

If you use gcc, you can compile with gcov support, which is enabled by the '--coverage' flag. Next, run your application or run your test suite with this gcov enabled build.

基本上 gcc 在编译期间会发出一些额外的文件,并且应用程序在运行时也会发出一些覆盖率数据.您必须收集所有这些(.gcdo 和 .gcda 文件).我不会在这里详细介绍,但您可能需要设置两个环境变量以合理的方式收集覆盖数据:GCOV_PREFIX 和 GCOV_PREFIX_STRIP...

Basically gcc will emit some extra files during compilation and the application will also emit some coverage data while running. You have to collect all of these (.gcdo and .gcda files). I'm not going in full detail here, but you probably need to set two environment variables to collect the coverage data in a sane way: GCOV_PREFIX and GCOV_PREFIX_STRIP...

运行后,您可以将所有覆盖率数据放在一起,并通过 lcov 工具套件运行.合并来自不同测试运行的所有覆盖文件也是可能的,尽管有点复杂.

After the run, you can put all the coverage data together and run it through the lcov toolsuite. Merging of all the coverage files from different test runs is also possible, albeit a bit involved.

无论如何,您最终会得到一组不错的网页,其中显示了一些覆盖率信息,指出了没有覆盖率因此未使用的代码段.

Anyhow, you end up with a nice set of webpages showing some coverage information, pointing out the pieces of code that have no coverage and hence, were not used.

当然,您需要仔细检查代码部分是否在任何情况下都没有使用,这在很大程度上取决于您的测试对代码库的运用程度.但至少,这将给出关于可能的死代码候选者的想法......

Off course, you need to double check if the portions of code are not used in any situation and a lot depends on how good your tests exercise the codebase. But at least, this will give an idea about possible dead-code candidates...

这篇关于遗留 C/C++ 项目中的死代码检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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