ThazKool said:
I am just wondering if all the methods that are never called upon
during a programs execution are removed when optimizing. For example
you have:
class FooA
{
void a();
...
void z();
}
class FooB ... class FooZ
You use only one method from FooA.c()
Another from FooB.h() and FooC.e(). Shouldn't only the 3 methods
mentioned become added to the final exe file?
What you can typically expect from the crufty compiler and linker
technology is roughly this:
1. Individual object files that are not referenced are removed during
linking.
2. If an object file contains any external symbol that is referenced
somewhere, the
entire object file is linked to the target, bringing in all the
unused parts with it.
3. The compiler itself may do a good job removing unused functions and
objects
which are private to a compilation unit (declared static).
4. Unused inline functions are usually treated well.
The reason for 2 is that many object file formats simply cannot be
edited to delete a function. They may contain internal references among
the functions which are already resolved: for instance,
program-counter-relative branches from one function to another. The
compiler emits the translation unit image all at once, and knows the
displacement between all the instruction. Calling a function can then
be done using a relocatable relative branch: ``call the function that
is 1549 bytes up from this point''. To delete some code in between
would require all those references which jump across that code to be
decoded and patched, which would require the linker to understand that
machine language.
The last time I looked at the sources for the GNU C compiler, the build
system used a gross hack in order to build the run-time support library
libgcc.a in order to make the library as small as possible. #ifdef
statements were used to divide up the library source file into sections
containing a single function, and it was passed through the compiler
many times, with different preprocessor symbols defined to select
individual functions for compilation, resulting in a separate .o file
for each function. Thus if that run-time function is not used, it
doesn't end up linked to the executable.
If your compiler doesn't support function-level linking, and you
really, really want to remove unused functions, what you can do is put
them into separate source files. Have the class declaration in a single
..h of course, but the implementations of the member functions can be
split into multiple files.
Watch out for virtuals. If a function is virtual, then typically, it's
as good as called. Even if you don't use that function, most compilers
generate object code that requires the functions to be there (e.g. a
virtual containing a symbolic reference to the function which must
resolve).