How to find classes without references in the code base

We are in the development period, where there is a lot of code that is being created, which can be short-lived, as it effectively creates forests, which at some point are replaced by something else, but will often continue to exist and be forgotten about.

Are there any good methods for finding classes in a database that are not used? Obviously, there will be many false positives (for example, library classes: you cannot use all the standard containers, but you want to know that they are), but if they were listed in the directory, this can make it easier to look at a glance.

I could write a script that greps for everyone class XXXand then looks for all instances again, but should omit the results for the cpp file in which the class methods were defined. It would also be incredibly slow - O (N ^ 2) for the number of classes in the codebase

Code coverage tools are not really an option here, since it has a graphical interface that cannot easily perform all the functions programmatically.

The platforms are Visual Studio 2013 or Xcode / clang

EDIT: I don't think this is a duplicate of the dead code question. Although there is overlap, identifying dead or inaccessible code is not exactly the same as searching for unaccepted classes.

+4
source share
2 answers

script, , , , . , , - ( cpp). , script ctags . grep , ( : ), , , , , 1 2 .

#!/bin/bash
CLASSDIR=${1:-}
USAGEDIR=${2:-}

if [ "${CLASSDIR}" = "" -o "${USAGEDIR}" = "" ]; then 
    echo "Usage: find_unreferenced_classes.sh <classdir> <usagedir>"
    exit 1
fi

ctags --recurse=yes --languages=c++ --c++-kinds=c -x $CLASSDIR | awk '{print $1}' | uniq > tags
[ -f "counts" ] && rm counts

for class in `cat tags`;
do
    count=`grep -l -r $class $USAGEDIR --include=*.h --include=*.cpp | wc -l`
    echo "$count $class" >> counts
done

sort -n counts

:

1 SomeUnusedClassDefinedInHeader
2 SomeUnusedClassDefinedAndDeclaredInHAndCppFile
10 SomeClassUsedLots
0

linux, g++, .

, , . , , .

struct A
{
  A () { }
};

struct B
{
  B () { }
};

struct C
{
  C () { }
};

void bar ()
{
  C c;
}

int main ()
{
  B b;
}

Linux, nm :

00000000004005bc T _Z3barv
00000000004005ee W _ZN1BC1Ev
00000000004005ee W _ZN1BC2Ev
00000000004005f8 W _ZN1CC1Ev
00000000004005f8 W _ZN1CC2Ev

, "A" .

SO-, g++ , :

:

00000000004005ba W _ZN1BC1Ev
00000000004005ba W _ZN1BC2Ev

, , Linux, , A, C.

+1

Source: https://habr.com/ru/post/1544123/


All Articles