我有遗留的c++代码,我应该删除不使用的代码。问题是代码库很大。
我如何才能知道哪些代码从未被调用/从未被使用?
我有遗留的c++代码,我应该删除不使用的代码。问题是代码库很大。
我如何才能知道哪些代码从未被调用/从未被使用?
当前回答
真正的答案是:你永远无法真正确定。
至少,对于重要的情况,你不能确定你已经得到了全部。考虑以下来自维基百科关于不可达代码的文章:
double x = sqrt(2);
if (x > 5)
{
doStuff();
}
正如维基百科正确指出的那样,一个聪明的编译器也许能够捕捉到这样的东西。但是考虑一下修改:
int y;
cin >> y;
double x = sqrt((double)y);
if (x != 0 && x < 1)
{
doStuff();
}
Will the compiler catch this? Maybe. But to do that, it will need to do more than run sqrt against a constant scalar value. It will have to figure out that (double)y will always be an integer (easy), and then understand the mathematical range of sqrt for the set of integers (hard). A very sophisticated compiler might be able to do this for the sqrt function, or for every function in math.h, or for any fixed-input function whose domain it can figure out. This gets very, very complex, and the complexity is basically limitless. You can keep adding layers of sophistication to your compiler, but there will always be a way to sneak in some code that will be unreachable for any given set of inputs.
还有一些输入集是永远不会被输入的。输入在现实生活中没有意义,或者在其他地方被验证逻辑阻塞。编译器没有办法知道这些。
这样做的最终结果是,虽然其他人提到的软件工具非常有用,但您永远无法确定您捕获了所有内容,除非您随后手动检查代码。即便如此,你也无法确定自己是否错过了什么。
恕我直言,唯一真正的解决方案是尽可能保持警惕,使用自动化,尽可能地重构,并不断寻找改进代码的方法。当然,这样做是个好主意。
其他回答
我有个朋友今天问了我这个问题,我看了看一些有前途的Clang开发,例如ASTMatchers和Static Analyzer,它们可能在编译过程中有足够的可见性来确定死代码部分,但后来我发现了这个:
https://blog.flameeyes.eu/2008/01/today-how-to-identify-unused-exported-functions-and-variables
它几乎完整地描述了如何使用一些GCC标志,这些标志似乎是为了识别未引用的符号而设计的!
If you are on Linux, you may want to look into callgrind, a C/C++ program analysis tool that is part of the valgrind suite, which also contains tools that check for memory leaks and other memory errors (which you should be using as well). It analyzes a running instance of your program, and produces data about its call graph, and about the performance costs of nodes on the call graph. It is usually used for performance analysis, but it also produces a call graph for your applications, so you can see what functions are called, as well as their callers.
这显然是对页面其他地方提到的静态方法的补充,它只会有助于消除完全不使用的类、方法和函数——它不会帮助找到实际调用的方法内部的死代码。
我认为您正在寻找一个代码覆盖工具。代码覆盖工具将在代码运行时分析它,它将让您知道哪些代码行被执行了,执行了多少次,以及哪些代码没有执行。
您可以尝试使用这个开源代码覆盖工具:TestCocoon—用于C/ c++和c#的代码覆盖工具。
我自己没有使用过cppcheck,但它声称可以找到未使用的函数。这也许不能完全解决问题,但可能是个开始。
一种方法是使用调试器和编译器特性,在编译过程中消除未使用的机器代码。
一旦某些机器代码被删除,调试器就不会让你在相应的源代码行上添加断点。因此,您将断点放置在任何地方,并启动程序并检查断点——那些处于“此源未加载代码”状态的断点对应于已消除的代码——要么该代码从未被调用,要么已内联,您必须执行一些最小分析,以找出这两者中哪一个发生了。
至少这是它在Visual Studio中的工作方式,我猜其他工具集也可以做到这一点。
这需要做很多工作,但我认为比手动分析所有代码要快。