How to find unused attributes/methods in Visual C++ 2008 - c++

Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.
Thanks,
Florian
Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.

Try PC-Lint. It's pretty good at finding redundant code.
I haven't tried version 9 yet. Version 8 does take some time to configure.
Try the online interactive demo.

I have not personally used their productivity tools (I use their windows control suit), but it looks like DevExpress has a C++ refactor'er called Refactor! for C++. I didn't immediately spot the features that you are looking for, but maybe they have it?

Coverage Validator can show unused C++ code (but not attributes). It does it dynamically so you have to 'exersize' the app to get the results:
http://successfulsoftware.net/2008/03/10/coverage-validator/

The tricky bit is that many functions in C++ have to exist, even if they are not called.
Boost especially will cause this, but even the regular STL code can do this. And your code has to play along. You might define a copy ctor because std::vector formally requires it. But if you don't instantiate any std::vector member that actually does copy a T, your copy ctor will remain unused.
Even if they don't have to, they often exist for safety. For example, declaring a private copy constructor can prevent an object from unintended copying. Without the private declaration, the compiler would define a public, memberwise copy ctor for you. Now, is this "unused" and do you want to be warned about them?

PC-Lint is very powerful, but hard to lean. Of course that pretty well describes C and C++ doesn't it?
Another tool I think is excellent is Whole Tomato's Visual Assist X which integrates right into the IDE.
There are some big gotchas in C++ when searching for unreferenced code: templates, callbacks, and message handlers may be critical to your project but are never directly called. For example the handler for a thread is not called directly, but is a parameter when you create a new thread. The "On_buttonpress" type messages in MFC or WTL projects will also show up as un-called methods.
Once you find them you can configure PC-Lint to ignore these, but the first time through its a lot of work.

nDepend will do it, along with cleaning your house and taking the dog for a walk. There's a nagware version available for free.
The following code query language statement will get you a list of unused methods
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE MethodCa == 0 AND
!IsPublic AND !IsEntryPoint AND !IsExplicitInterfaceImpl AND
!IsClassConstructor AND !IsFinalizer

Related

What's the deal with the CRT SECURE warnings/errors on visual studio?

I encountered this issue a dozen, if not a million times already: I compile a c++ program on visual studio and get a dozen, if not a million warnings and/or errors suggesting that I am doing something very dangerous and that there is no way my compiler will let me do that. the warnings/errors tell me that I am using a deprecated function and that I should consider using some other safer function that may or may not do the same thing as this one, but I have no idea what this one does in the first place since I did not write it.
After some research (I do it everytime, I am not a quick learner) I find out I am not the first one facing this particular problem, and I can coerce my compiler to work with this program with the proper macro definition (for the future readers who don't care about my question but want to compile their program, you have to define _CRT_SECURE_NO_DEPRECATE, don't you ever dare following visual studio's advice and using the allegedly safe function).
I have often read in the manual or on this very website, along with the answer, the fact that I should not do that if I don't know precisely what I am doing.
I must confess: I have no idea what I am doing, and I would be very grateful if someone would accept to explain it to me.
So here are my questions:
What are those functions that are unsafe? Why do they exist in the first place?
What is unsafe about them?
Why are they so often found in perfectly honourable libraries?
I have come to the understanding that there is no safe and portable alternative to those functions: why is it so? How about we have some people think about it and try to define a way to do it, and everyone would accept to do it that way, and we would call it standard maybe?
To tackle your questions in order:
They exist in the first place because the standard wrote them in such a way. Standards authors are human so don't think of everything and this left some security weaknesses in the C API. You can find a list of these deprecated functions at http://msdn.microsoft.com/en-us/library/ms235384.aspx.
Many of the functions are unsafe as they allow such things as buffer overruns to occur but other security vulnerabilities may be exposed depending on the function.
Honourable libraries generally try for some cross platform compatibility so I suspect will try to stick to stand C rather than using compiler specific functions and extensions.
The "perfect" standard will probably never exist as in my first point :) Some of the C API problems can be avoided using C++ but that's a big hammer to crack a small nut and brings security vulnerabilities of its own.

Is there a way to get a call graph for certain c++ function in Visual Studio?

I wonder whether there is a tool for VS that can show me a call graph (that is, a diagram listing all possible execution paths) for a given C++ function. It would help in navigating a big code base, in cases where a function is called in only a few places.
For oft-called functions like printf it could simply say:
too many options...
Again I guess it is not really easy to make such tool so I wonder if it exists, but you know it seems possible to do it so you never know... :)
EDIT: I know about find all references, but that gives just call sites of the function, not the call site of the function that called the function that called the function...
EDIT: VS is 2010, but if necessary VS2012 is an option.
You mentioned that you know about finding all the references. Have you looked into viewing the Call Hierarchy? It's probably not your "dream method" but it does allow you to look at a function in terms of "calls to" and "calls from" the given function. The window also allows you to add multiple functions to view in a tree format. So basically you would tree up or down through the possible outcomes.
Right click on the desired method ( could be anywhere in the hierarchy ) =>
Select "View Call Hierarchy"
Note that if you can add more than one reference point to the window. Delete when needed
You could also use Ctrl+K or Ctrl+T
Another fine example, IMHO, of a disappointment in the differences between C++ and C# with VS. I think Code Maps would be just what you're looking for. Assuming of course you were working with Ultimate - but nope, not with C++.
There's no such feature in C++/MSVC, as far as I know.
However, there's AQTime profiler for windows that has "static analysis" option that (IF I remember correctly) scans compiled executable, generates call graph and shows you unreacheable functions.
If I remember correctly, AQtime integrates into visual studio (professional edition, afaik).
Unfortunately, this is a commercial profiler that costs around $500, and this feature is not available in trial version. Last time I used static analysis was 3..4 years ago and I don't exactly remember details at the moment (and I don't have access to AQTime anymore). Anyway, it is a specialized tool, so I wouldn't recommend buying it unless you're optimizing code for speed 24/7.
Perhaps, by googling "static analysis", "code coverage" or researching other profilers you'll find somewhat similar tool that does the job for free.
Aside from that, doxygen can generate callgraphs for C++ code. In case of doxygen, you'll have to hunt for functions that are never called yourself.
Also, Visual Studio 2008 had a built-in caller graph feature (which, I think, uses intellisense). Basically, you right click any function and select "show callers" (or something like that), that'll open list of all functions (visual studio THINKS are calling your function) in a window. Because this feature was present in VS2008, it should be included in VS2010. However, it can't detect every caller for obvious reasons (virtual methods, callbacks, etc).
Maybe doxygen is the tool you are looking for. It provides the possibility to generate call graphs (showing all functions called by a specific function) and/or caller graphs(showing the functions that the function is directly or indirectly called by).
see: http://www.doxygen.nl/manual/diagrams.html
Take a look at Understand tool (http://www.scitools.com). It's great for drawing call graphs and control flow charts.Unfortunately, it's commercial.
You can resolve results after doing Symbol search. Just right click in your source and then select find all references that performs symbol search. Its explained in further details at http://blogs.msdn.com/b/vcblog/archive/2009/11/17/improvements-to-find-all-references-in-visual-studio-2010.aspx
You can try CppDepend which give you the call graph inside VS and provides many features in its dependency graph.
Source Navigator is a tool that I have used and have been quite happy with on C++ projects. Again, it is not within the Visual Studio IDE, but it has some great advantages if you don't mind pressing Alt-Tab :-)
works with both C and C++ sources
is quite fast in it's indexing and searching; it's a pleasure to use, IMHO
is a visual tool
is a free and Open Source tool
See http://sourcenav.berlios.de/screenshots/ for some screenshots
In particular, you are looking for the Cross-Reference Browser:
"It can find every call of a function, or tell you everything a
particular function calls. It creates tree diagrams that show
essential relationships within the project's symbol database, such as
the function call hierarchy tree. You can traverse up and down the
hierarchy tree, as well as expand or restrict the tree. You can select
items in the hierarchy and display their Refers-to and Referred-by
relationships; these relationships are based on the "point-of-view" of
the selected symbol."
Though this example screenshot from the tutorial, "Using the Cross-Reference Browser" shows Referred-by relationships (using red arrows) for a class and not a function, the latter use case would be very similar. You can also browse what functions / methods are getting called from a function, and that would be a Refers-to relationship, shown using blue arrows instead of red.
Do give it a try! As I mentioned before, I have been a happy user of this tool; it's not very well-known, but is a good piece of software (that also stands as an example for how useful Tcl/Tk can be in the right hands).
I think you should be able to use VS Plugin - CodeGraph on your solution and look for the specific function you are looking for and go on from there. It does static analysis on your solution and generates a nice graph of the call flows. Check "https://marketplace.visualstudio.com/items?itemName=YaobinOuyang.CodeAtlas". Hope this helps.

Can anyone explain the DYNAMIC_CLASSes in a few terms?

I've been developing for some time. And these beasts appear from time to time in MFC, wxWidgets code, and yet I can't find any info on what they do exactly.
As I understand, they appeared before dynamic_cast was integrated into core C++. And the purpose, is to allow for object creation on the fly, and runtime dynamic casts.
But this is where all the information I found, ends.
I've run into some sample code that uses DECLARE_DYNAMIC_CLASS and IMPLEMENT_DYNAMIC_CLASS within a DLL, and that is used for exported classes. And this structure confuses me.
Why is it done this way? Is that a plugin based approach, where you call LoadLibrary and then call the CreateDynamicClass to get a pointer which can be casted to the needed type?
Does the DECLARE/IMPLEMENT_DYNAMIC work over DLL boundaries? Since even class is not so safe to DLLEXPORT, and here we have a custom RTTI table in addition to existing problems.
Is it possible to derive my class from a DYNAMIC_CLASS from another DLL, how would it work?
Can anyone please explain me what these things are for, or where I can find more than a two sentences on a topic?
This stuff appends addional type information to your class, which allows to RTTI in runtime-independent manner, possibility of having factories to create your classes and many other things. You can find similar approach at COM, QMetaObject, etc
Have you looked at the definitions of DECLARE/IMPLEMENT_DYNAMIC?
In the MS world, all uppercase usually denotes a macro, so you can just look up the definition and try to work out what it's doing from there. If you're in Visual Studio, there's a key you can hit to jump to the definition - see what it says, and look that up and try to work from there.

How can I check if virtual methods are used inside constructors/destructors?

I'm sure that the big project I'm working on is plagued with this problem. Once, I even had to debug a bug related to that.
Is it possible to write some sort of smart code that would catch this kind of calls? Or, perhaps, there are tools that can help to find these and other types of problems? (I'm using vs2008).
Scott Meyers page lists several code checking tools (PC-Lint, CodeCheck, and CodeAdvisor) capable of issuing warnings for calls of virtual functions from constructors.

C++ Developer Tools: The Dark Areas [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
While C++ Standards Committee works hard to define its intricate but powerful features and maintain its backward compatibility with C, in my personal experience I've found many aspects of programming with C++ cumbersome due to lack of tools.
For example, I recently tried to refactor some C++ code, replacing many shared_ptr by T& to remove pointer usages where not needed within a large library. I had to perform almost the whole refactoring manually as none of the refactoring tools out there would help me do this safely.
Dealing with STL data structures using the debugger is like raking out the phone number of a stranger when she disagrees.
In your experience, what essential developer tools are lacking in C++?
My dream tool would be a compile-time template debugger. Something that'd let me interactively step through template instantiations and examine the types as they get instantiated, just like the regular debugger does at runtime.
In your experience, what essential developer tools are lacking in C++?
Code completion. Seriously. Refactoring is a nice-to-have feature but I think code completion is much more fundamental and more important for API discoverabilty and usabilty.
Basically, tools that require any undestanding of C++ code suck.
Code generation of class methods. When I type in the declaration you should be able to figure out the definition. And while I'm on the topic can we fix "goto declaration / goto definition" always going to the declaration?
Refactoring. Yes I know it's formally impossible because of the pre-processor - but the compiler could still do a better job of a search and replace on a variable name than I can maually. You could also syntax highlight local, members and paramaters while your at it.
Lint. So the variable I just defined shadows a higher one? C would have told me that in 1979, but c++ in 2009 apparently prefers me to find out on my own.
Some decent error messages. If I promise never to define a class with the same name inside the method of a class - do you promise to tell me about a missing "}". In fact can the compiler have some knowledge of history - so if I added an unbalanced "{" or "(" to a previously working file could we consider mentioning this in the message?
Can the STL error messages please (sorry to quote another comment) not look like you read "/dev/random", stuck "!/bin/perl" in front and then ran the tax code through the result?
How about some warnings for useful things? "Integer used as bool performance warning" is not useful, it doesn't make any performance difference, I don't have a choice - it's what the library does, and you have already told me 50 times.
But if I miss a ";" from the end of a class declaration or a "}" from the end of a method definition you don't warn me - you go out of your way to find the least likely (but theoretically) correct way to parse the result.
It's like the built in spell checker in this browser which happily accepts me misspelling wether (because that spelling is an archaic term for a castrated male goat! How many times do I write about soprano herbivores?)
How about spell checking? 40 years ago mainframe Fortran compilers had spell checking so if misspelled "WRITE" you didn't come back the next day to a pile of cards and a snotty error message. You got a warning that "WRIET" had been changed to WRITE in line X. Now the compiler happily continues and spends 10mins building some massive browse file and debugger output before telling you that you misspelled prinft 10,000 lines ago.
ps. Yes a lot of these only apply to Visual C++.
pps. Yes they are coming with my medication now.
If talking about MS Visual Studio C++, Visual Assist is a very handy tool for code completition, some refactorings - e.g. rename all/selected references, find/goto declaration, but I still miss the richness of Java IDEs like JBuilder or IntelliJ.
What I still miss, is a semantic diff tool - you know, one which does not compare the two files line-by-line, but statements/expressions. What I've found on the internet are only some abandoned tries - if you know one, please write in comment
The main problem with C++ is that it is hard to parse. That's why there are so very few tools out there that work on source code. (And that's also why we're stuck with some of the most horrific error messages in the history of compilers.) The result is, that, with very few exceptions (I only know doxygen and Visual Assist), it's down to the actual compiler to support everything needed to assist us writing and massaging the code. With compilers traditionally being rather streamlined command line tools, that's a very weak foundation to build rich editor support on.
For about ten years now, I'm working with VS. meanwhile, its code completion is almost usable. (Yes, I'm working on dual core machines. I wouldn't have said this otherwise, wouldn't I?) If you use Visual Assist, code completion is actually quite good. Both VS itself and VA come with some basic refactoring nowadays. That, too, is almost usable for the few things it aims for (even though it's still notably less so than code completion). Of course, >15 years of refactoring with search & replace being the only tool in the box, my demands are probably much too deteriorated compared to other languages, so this might not mean much.
However, what I am really lacking is still: Fully standard conforming compilers and standard library implementations on all platforms my code is ported to. And I'm saying this >10 years after the release of the last standard and about a year before the release of the next one! (Which just adds this: C++1x being widely adopted by 2011.)
Once these are solved, there's a few things that keep being mentioned now and then, but which vendors, still fighting with compliance to a >10 year old standard (or, as is actually the case with some features, having even given up on it), never got around to actually tackle:
usable, sensible, comprehensible compiler messages (como is actually pretty good, but that's only if you compare it to other C++ compilers); a linker that doesn't just throw up its hands and says "something's wrong, I can't continue" (if you have taught C++ as a first language, you'll know what I mean); concepts ('nuff said)
an IO stream implementation that doesn't throw away all the compile-time advantages which overloading operator<<() gives us by resorting to calling the run-time-parsing printf() under the hood (Dietmar Kühl once set out to do this, unfortunately his implementation died without the techniques becoming widespread)
STL implementations on all platforms that give rich debugging support (Dinkumware is already pretty good in that)
standard library implementations on all platforms that use every trick in the book to give us stricter checking at compile-time and run-time and more performance (wnhatever happened to yasli?)
the ability to debug template meta programs (yes, jalf already mentioned this, but it cannot be said too often)
a compiler that renders tools like lint useless (no need to fear, lint vendors, that's just wishful thinking)
If all these and a lot of others that I have forgotten to mention (feel free to add) are solved, it would be nice to get refactoring support that almost plays in the same league as, say, Java or C#. But only then.
A compiler which tries to optimize the compilation model.
Rather than naively include headers as needed, parsing them again in every compilation unit, why not parse the headers once first, build complete syntax trees for them (which would have to include preprocessor directives, since we don't yet know which macros are defined), and then simply run through that syntax tree whenever the header is included, applying the known #defines to prune it.
It could even be be used as a replacement for precompiled headers, so every header could be precompiled individually, just by dumping this syntax tree to the disk. We wouldn't need one single monolithic and error-prone precompiled header, and would get finer granularity on rebuilds, rebuilding as little as possible even if a header is modified.
Like my other suggestions, this would be a lot of work to implement, but I can't see any fundamental problems rendering it impossible.
It seems like it could dramatically speed up compile-times, pretty much rendering it linear in the number of header files, rather than in the number of #includes.
A fast and reliable indexer. Most of the fancy features come after this.
A common tool to enforce coding standards.
Take all the common standards and allow you to turn them on/off as appropriate for your project.
Currently just a bunch of perl scrips usullay has to supstitute.
I'm pretty happy with the state of C++ tools. The only thing I can think of is a default install of Boost in VS/gcc.
Refactoring, Refactoring, Refactoring. And compilation while typing. For refactorings I am missing at least half of what most modern Java IDEs can do. While Visual Assist X goes a long way, a lot of refactoring is missing. The task of writing C++ code is still pretty much that. Writing C++ code. The more the IDE supports high level refactoring the more it becomes construction, the more mallable the structure is the easier it will be to iterate over the structure and improve it. Pick up a demo version of Intellij and see what you are missing. These are just some that I remember from a couple of years ago.
Extract interface: taken a view classes with a common interface, move the common functions into an interface class (for C++ this would be an abstract base class) and derive the designated functions as abstract
Better extract method: mark a section of code and have the ide write a function that executes that code, constructing the correct parameters and return values
Know the type of each of the symbols that you are working with so that not only command completion can be correct for derived values e.g. symbol->... but also only offer functions that return the type that can be used in the current expression e.g. for
UiButton button = window->...
At the ... only insert functions that actually return a UiButton.
A tool all on it's own: Naming Conventions.
Intelligent Intellisense/Code Completion even for template-heavy code.
When you're inside a function template, of course the compiler can't say anything for sure about the template parameter (at least not without Concepts), but it should be able to make a lot of guesses and estimates. Depending on how the type is used in the function, it should be able to narrow the possible types down, in effect a kind of conservative ad-hoc Concepts. If one line in the function calls .Foo() on a template type, obviously a Foo member method must exist, and Intellisense should suggest it in the rest of the function as well.
It could even look at where the function is invoked from, and use that to determine at least one valid template parameter type, and simply offer Intellisense inside the function based on that.
If the function is called with a int as a template parameter, then obviously, use of int must be valid, and so the IDE could use that as a "sample type" inside the function and offer Intellisense suggestions based on that.
JavaScript just got Intellisense support in VS, which had to overcome a lot of similar problems, so it can be done. Of course, with C++'s level of complexity, it'd be a ridiculous amount of work. But it'd be a nice feature.