Reputation: 37836
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.
Upvotes: 6
Views: 1362
Reputation: 119877
The standard library is normally shared, so it does not take any space in your executable.
If you link statically, then, as far as the linker is concerned, non-virtual member functions are just your regular garden variety functions with funny names. Whatever the linker can do with normal functions, it can do with non-virtual members. I think GNU LD may be able to remove unused functions on certain architectures but not on others.
Of course, function templates, such as the members of std::string
are a different story altogether. To the linker, they don't come from the library at all, but from your objects (and only those you did instantiate).
Upvotes: 0
Reputation: 1
This answer doesn't exactly cover your case, but if you want to know if there are any uncalled functions of YOUR classes some static analysis tools like cppcheck will report this.
Upvotes: 0
Reputation: 1747
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.
Upvotes: 4