Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can unused member functions be reported by the linker? (C++)(gcc)

std::string has over 30 member functions that can be called on a string object.
What if I only use a few of them?

I assume the unused member functions will not take up space in the executable code section.
I'm curious to know whether or not it's possible for the linker to determine a member function unused, remove it from being part of the compiled binary, and report what functions it threw away.
Is there any way to do this? I was looking at gcc's linker flags, but I couldn't find anything relevant.

like image 680
Trevor Hickey Avatar asked May 28 '12 18:05

Trevor Hickey


People also ask

Does linker remove unused functions?

So the linker is able to remove each individual function because it is in its own section. So enabling this for your library will allow the linker to remove unused functions from the library.

Do unused functions get compiled?

No: for unused globally available functions. The compiler doesn't know if some other compilation unit references it. Also, most object module types do not allow functions to be removed after compilation and also do not provide a way for the linker to tell if there exist internal references.


1 Answers

Since std::string is a template class (std::string is only a typedef to std::basic_string<char>), only the used methods will be instantiated, so no unused methods will ever be compiled and so they can't be removed from your executable.

Regarding non-template classes: virtual functions will always end up in the executable, regardless whether they are called, because there address is needed for the vtable. Other methods (as well as free functions), coming from the source of the executable or statically linked libraries, will only be linked into the binary if they are actually used. But I know of no linker flag to print the functions which have not been linked in.

A shared library (.so) on the other hand, has to include all (exported) functions and methods, because a binary using this shared library could use any (exported) function. But since a shared library can be used by many executables while being loaded into memory only once, this is usually worth it.

like image 150
Florian Sowade Avatar answered Oct 04 '22 04:10

Florian Sowade