Dead code detection in legacy C/C++ project [close

2019-01-05 09:42发布

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?

8条回答
The star\"
2楼-- · 2019-01-05 10:25

Dead code analysis like this requires a global analysis of your entire project. You can't get this information by analyzing translation units individually (well, you can detect dead entities if they are entirely within a single translation unit, but I don't think that's what you are really looking for).

We've used our DMS Software Reengineering Toolkit to implement exactly this for Java code, by parsing all the compilation-units involved at once, building symbol tables for everything and chasing down all the references. A top level definition with no references and no claim of being an external API item is dead. This tool also automatically strips out the dead code, and at the end you can choose what you want: the report of dead entities, or the code stripped of those entities.

DMS also parses C++ in a variety of dialects (EDIT Feb 2014: including MS and GCC versions of C++14 [EDIT Nov 2017: now C++17]) and builds all the necessary symbol tables. Tracking down the dead references would be straightforward from that point. DMS could also be used to strip them out. See http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html

查看更多
孤傲高冷的网名
3楼-- · 2019-01-05 10:26

For C code only and assuming that the source code of the whole project is available, launch an analysis with the Open Source tool Frama-C. Any statement of the program that displays red in the GUI is dead code.

If you have "dead code" problems, you may also be interested in removing "spare code", code that is executed but does not contribute to the end result. This requires you to provide an accurate modelization of I/O functions (you wouldn't want to remove a computation that appears to be "spare" but that is used as an argument to printf). Frama-C has an option for pointing out spare code.

查看更多
登录 后发表回答