Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find All Callers of a Function in C++?

I'm refactoring some code in C++, and I want to deprecate some old methods. My current method for finding all of the methods looks like this:

  1. Comment out the original method in the source file in which I'm working.
  2. Try to compile the code.
  3. If a compiler error is found, then make a note comment out the call and try to recompile.
  4. Once the compile has completed successfully, I've found all of the calls.

This totally sucks. I've also tried grepping source for the name of the function calls, but I sometimes run into problems with functions of the same name with different arguments, so my compilation makes the C++ compiler resolve the names for me. I've found this question for C#, but my code base is entirely implemented in C++.

Is there a better way to find all of the callers of a class method or function in C++? I'm using GCC on Unix systems, but cross-platform solutions would be superlative.

like image 268
James Thompson Avatar asked Jul 16 '09 21:07

James Thompson


2 Answers

GCC allows you to decorate variables, functions, and methods with __attribute__((deprecated)), which will cause a warning on all callsites (unless -Wno-deprecated-declarations is given).

class A {
public:
    A() __attribute__((deprecated)) {}
};
int main() {
    A a;
}
$ g++ test.c
test.cc: In function ‘int main()’:
test.cc:6: warning: ‘A::A()’ is deprecated (declared at test.cc:3)
like image 55
ephemient Avatar answered Sep 17 '22 12:09

ephemient


Eclipse can do this without any plugins. It can be a useful tool for stuff like this even if you don't want to use it for your day-to-day editor.

  1. Download, install, and run the Eclipse CDT.
  2. Go under File, New, C++ Project. Enter a project name and choose an Empty Makefile project from the Project Type tree view. Uncheck "Use default location" and enter the folder where your project is kept.
  3. Click Next, then click Finish.
  4. Eclipse will automatically start indexing your project. If it really is a Makefile project, and since you're using g++, you can do a full clean then build from within Eclipse (under the Project menu), and it should automatically use your existing makefiles and automatically discover your include directories and other project settings.
  5. Find the prototype of the overloaded function in a source file, right-click on it, choose References, and choose Project. Eclipse will find all references to that function, and only to that particular overload of that function, within your project.

You can also use Eclipse's built-in refactoring support to rename overloaded functions so that they're no longer overloaded. Eclipse is also fully cross-platform; you can use features like its indexer, search references, and refactoring even for projects that are maintained and built in other IDEs.

like image 28
Josh Kelley Avatar answered Sep 19 '22 12:09

Josh Kelley