How to detect code duplication during development?

C++Code Duplication

C++ Problem Overview


We have a fairly large code base, 400K LOC of C++, and code duplication is something of a problem. Are there any tools which can effectively detect duplicated blocks of code?

Ideally this would be something that developers could use during development rather than just run occasionally to see where the problems are. It would also be nice if we could integrate such a tool with CruiseControl to give a report after each check in.

I had a look at Duploc some time ago, it showed a nice graph but requires a smalltalk environment to use it, which makes running it automatically rather difficult.

Free tools would be nice, but if there are some good commercial tools I would also be interested.

C++ Solutions


Solution 1 - C++

Simian detects duplicate code in C++ projects.

Update: Also works with Java, C#, C, COBOL, Ruby, JSP, ASP, HTML, XML, Visual Basic, Groovy source code and even plain text files

Solution 2 - C++

I've used PMD's Copy-and-Paste-Detector and integrated it into CruiseControl by using the following wrapper script (be sure to have the pmd jar in the classpath).

Our check runs nightly. If you wish to limit output to list only files from the current change set you might need some custom programming (idea: check all and list only duplicates where one of the changed files is involved. You have to check all files because a change could use some code from a non-changed file). Should be doable by using XML output and parsing the result. Don't forget to post that script when it's done ;)

For starters the "Text" output should be ok, but you will want to display the results in a user-friendly way, for which i use a perl script to generate HTML files from the "xml" output of CPD. Those are accessible by posting them to the tomcat where cruise's reporting jsp resides. The developers can view them from there and see the results of their dirty hacking :)

It runs quite fast, less than 2 seconds on 150 KLoc code (empty lines and comments not counted in that number).

duplicatecheck.xml:

<project name="duplicatecheck" default="cpd">

<property name="files.dir" value="dir containing your sources"/>
<property name="output.dir" value="dir containing results for publishing"/>

<target name="cpd">
    <taskdef name="cpd" classname="net.sourceforge.pmd.cpd.CPDTask"/>
    <cpd minimumTokenCount="100" 
    	 language="cpp" 
    	 outputFile="${output.dir}/duplicates.txt"
    	 ignoreLiterals="false"
    	 ignoreIdentifiers="false"
    	 format="text">
        <fileset dir="${files.dir}/">
            <include name="**/*.h"/>
            <include name="**/*.cpp"/>
                <!-- exclude third-party stuff -->
            <exclude name="boost/"/>
            <exclude name="cppunit/"/>
        </fileset>
    </cpd>
</target>

Solution 3 - C++

http://duplo.giants.ch/">duplo</a> appears to be a C implementation of the algorithm used in Duploc. It is simple to compile and install, and while the options are limited it seems to more or less work out-of-the-box.

Solution 4 - C++

These Debian packages seem to do something along these lines:

P.S. There ought to be a debtags tag for all tools related for finding [near] duplication. (But what would it be called?)

Solution 5 - C++

Look at the PMD project.

I've never used it, but have always wanted to.

Solution 6 - C++

Well, you can run a clone detector on your source code base every night.

Many clone detectors work by comparing source lines, and can only find exact duplicate code.

CCFinder, above, works by comparing language tokens, so it isn't sensitive to white space changes. It can detect clones which are variants of the original code if there only single token changes (e.g, change a variable X to Y in the clone).

Ideally what you want is the above, but the ability to find clones where the variations are allowed to be relatively arbitrary, e.g., replace a variable by an expression, a statement by a block, etc.

Our CloneDR clone detector does this for Java, C#, C++, COBOL, VB.net, VB6, Fortran and a variety of other languages. It can be seen at: http://www.semdesigns.com/Products/Clone/index.html

As well as being able to handle multiple languages, CloneDR engine is capable of handling a variety of input encoding styles, including ASCII, ISO-8859-1, UTF8, UTF16, EBCDIC, a number of Microsoft encodings, and (Japanese) Shift-JIS.

The site has several clone detection run example reports, including one for C++.

EDIT Feb 2014: Now handles all of C++14.

Solution 7 - C++

CCFinderX is a free (for in-house use) cloned code detector that supports multiple programming languages (Java, C, C++, COBOL, VB, C#).

Solution 8 - C++

Same (http://sourceforge.net/projects/same/) is extremely plain, but it works on text lines instead of tokens, which is useful if you're using a language that isn't supported by one of the fancier clone finders.

Solution 9 - C++

There is also Simian which supports Java, C#, C++, C, Objective-C, JavaScript...

It's supported by Hudson (like CPD).

Unless you're an open source project, you must pay for Simian.

Solution 10 - C++

ConQAT is a great tool which suports C++ code analysis. Can find duplicates ignoring whitespace. Has extreamly handy gui and console interfaces. Because of it's flexibility it is not an easy to to setup. I've found this blog post very useful for setting up c++ project.

Solution 11 - C++

You can use our SourceMeter tool for detecting code duplication. It is a command line tool (very similar to compilers), so you can it easily integrate into continuous integration tools, like CruiseControl your mentioned, or Jenkins.

Solution 12 - C++

Finding "identical" code snippets is relatively easy, there are existing tool that already do this (see other answers).

Sometimes it's a good thing, sometimes it's not; it can bog down development time if done at a too fine "level"; i.e. trying to refactor so much code, you loose your goal (and probably bust your milestones and schedules).

What is harder is to find multiple function/method that do the same thing but with different (but similar) inputs and/or algorithm without proper documentation.

If you have to two or different methods to do the same thing and the programmer try to fix one instance but forget (or does not know they exist) to fix the other ones, you will increase the risk to your software.

Solution 13 - C++

TeamCity has a powerful code duplication engine for .NET and java, that can effortlessly run as part of your build system.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid DibbenView Question on Stackoverflow
Solution 1 - C++Simon SteeleView Answer on Stackoverflow
Solution 2 - C++user39039View Answer on Stackoverflow
Solution 3 - C++bennoView Answer on Stackoverflow
Solution 4 - C++SamBView Answer on Stackoverflow
Solution 5 - C++Andy LesterView Answer on Stackoverflow
Solution 6 - C++Ira BaxterView Answer on Stackoverflow
Solution 7 - C++bk1eView Answer on Stackoverflow
Solution 8 - C++Sean McMillanView Answer on Stackoverflow
Solution 9 - C++WernightView Answer on Stackoverflow
Solution 10 - C++user2648800View Answer on Stackoverflow
Solution 11 - C++Rudolf FERENCView Answer on Stackoverflow
Solution 12 - C++MaxView Answer on Stackoverflow
Solution 13 - C++ripper234View Answer on Stackoverflow