Is all code compiled and included on the final binary?

Suppose I create a class extension with hundreds of methods and I include that class in my project.

Now suppose that from that extension, I just use 2 or 3 methods. Remember that the class extension has hundreds of methods.

When I compile the code, what will be included in the binary?

Will it be just the methods I have used from that class extension or all of them, including the ones that were not used by that particular project?


Solution 1:

This can be divided into three categories:

  • Dynamic (shared) linking
  • Static linking, --whole-archive in GNU ld
  • Static linking, --no-whole-archive in GNU ld

(other linkers might have similar options).

Dynamic linking

The code will only include the method names from the library you are extending.

Static linking, whole archive

Oops... whole code of the other class will be included.

Static linking, no whole archive

Only the object files you use will be included. I suggest that, for large classes, you split the source code wherever possible.

Used methods

Despite the methods you explicitly use, each extending/override will require some symbols like vtable. Refer to your compiler documentation.