0

Can I identify unused C++ headers by looking at the symbols in the binary?

My end goal is to remove accidentally/unnecessary included C++ headers. Through some search, I realized there is no up-to-date, free, Linux tools available for this.

Detecting superfluous #includes in C/C++?

How should I detect unnecessary #include files in a large C++ project?

I am wondering whether it is possible to achieve this at a higher level, by looking at symbols. Scheme showing below:

image

mycomponent.cc includes component_1.hh and component_2.hh, and suppose component_2.hh is the unused include, and they are dynamically linked.

Here is the plan: Suppose I know all of the libraries I need to link to in the first place. If I get all the undefined symbols from mycomponent.so, say my_list, and compare it with all the defined symbols in component_1.so and component_2.so. If component_2.so contains no symbol from my_list. Then I would know that component_2.so is not needed, then I can go back to see what headers are from component_2 that shall be removed. Of course, this would only work if all the headers from component_2 are not used in my_component

Is this viable?

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
baltam
  • 43
  • 5

1 Answers1

1

Short answer - no. Whatever symbols are not actually used by code will get optimized away and not be in the final binary. And even if they weren't, there is no way to determine from the binary which header include(s) the sumbols originally came from.

What you are looking for is a source code analyzer, that will parse your source code and point out any issues with it, such as unused/unnecessary header includes.

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620