我有遗留的c++代码,我应该删除不使用的代码。问题是代码库很大。
我如何才能知道哪些代码从未被调用/从未被使用?
我有遗留的c++代码,我应该删除不使用的代码。问题是代码库很大。
我如何才能知道哪些代码从未被调用/从未被使用?
当前回答
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.
这显然是对页面其他地方提到的静态方法的补充,它只会有助于消除完全不使用的类、方法和函数——它不会帮助找到实际调用的方法内部的死代码。
其他回答
如果你使用g++,你可以使用这个标志-Wunused
根据文档:
Warn whenever a variable is unused aside from its declaration, whenever a function is declared static but never defined, whenever a label is declared but not used, and whenever a statement computes a result that is explicitly not used.
http://docs.freebsd.org/info/gcc/gcc.info.Warning_Options.html
编辑:这是另一个有用的标志-Wunreachable-code根据文档:
This option is intended to warn when the compiler detects that at least a whole line of source code will never be executed, because some condition is never satisfied or because it is after a procedure that never returns.
我认为您正在寻找一个代码覆盖工具。代码覆盖工具将在代码运行时分析它,它将让您知道哪些代码行被执行了,执行了多少次,以及哪些代码没有执行。
您可以尝试使用这个开源代码覆盖工具:TestCocoon—用于C/ c++和c#的代码覆盖工具。
如果某个函数将被调用的一般问题是np完全的。一般来说,你无法提前知道某个函数是否会被调用,就像你不知道图灵机是否会停止一样。如果存在从main()到您所编写的函数的某个路径(静态),则可以获取,但这并不保证它将被调用。
Mark as much public functions and variables as private or protected without causing compilation error, while doing this, try to also refactor the code. By making functions private and to some extent protected, you reduced your search area since private functions can only be called from the same class (unless there are stupid macro or other tricks to circumvent access restriction, and if that's the case I'd recommend you find a new job). It is much easier to determine that you don't need a private function since only the class you're currently working on can call this function. This method is easier if your code base have small classes and is loosely coupled. If your code base does not have small classes or have very tight coupling, I suggest cleaning those up first.
接下来将标记所有剩余的公共函数,并制作一个调用图,以找出类之间的关系。从这棵树上,试着找出树枝的哪一部分看起来可以修剪。
这种方法的优点是你可以在每个模块的基础上进行测试,所以当你的代码库损坏时,你很容易通过单元测试,而不会有很长一段时间。
如果你使用g++,你可以使用这个标志-Wunused
根据文档:
每当变量未使用时发出警告 除了它的声明,无论何时 函数被声明为静态的,但是 从来没有定义,每当一个标签 声明但未使用,并且每当a 语句计算的结果为 明确没有使用。
http://docs.freebsd.org/info/gcc/gcc.info.Warning_Options.html
编辑:这里是另一个有用的标志-Wunreachable-code 根据文档:
此选项用于在编译器检测到至少一整行源代码永远不会执行时发出警告,因为某些条件永远不会满足,或者因为它在一个永远不会返回的过程之后。
更新:我在遗留的C/ c++项目中发现了类似的主题死代码检测