1

Suppose I create an iOS application. I include a static library. I create an object of a class that is defined and implemented in static library. This object doesn't use other classes defined in the library. Will all of the static library be present in the application I build? The idea is that much of the static library contains unused code and wouldn't need to be present.

I believe there a flags that help determine the behavior -- if someone can spell out how this works, I sure would appreciate it.

Ben Flynn
  • 17,294
  • 18
  • 92
  • 133
  • The linker will not include things that it doesn't think need to be present. You can use the `nm` command to view what symbols got placed into your output executable. There are flags to tell the linker to not get rid of a particular symbol it finds to be unused, but it's rare that you would need to do that. – mah Sep 16 '15 at 16:17
  • 1
    @mah Thanks. Would -force_load -all_load be flags that pull in all symbols? What about -ObjC? Does the linker have an idea of optimization levels where it does a more or less aggressive search for unused symbols? – Ben Flynn Sep 16 '15 at 16:51
  • `-Wl,-exported_symbol,_nameOfSymbol` is a flag to indicate that `nameOfSymbol()` must be exported (therefore not removed) (note the underscore preceding the symbol name in the flag, and note that `-Wl,` says that what follows goes from `clang` to the linker). I'm not certain how ObjectiveC classes/symbols are treated but I expect they would all be kept since ObjC's runtime lets you get very creative in ways the compiler/linker cannot hope to recognize. I'm not familiar with either of -force_load nor -all_load, but you could figure out if either keeps symbols by using `nm` on the output. – mah Sep 16 '15 at 17:01

1 Answers1

1

A static library is an archive of object files. If you link against a static library libfoo.a then the linker by default will link into your final executable all and only those object files in libfoo.a that are required to provide definitions for the public symbols that are referenced by the program.

More specifically, if the linker finds the library requested (via the option -lfoo) at a given point in the commandline sequence of object files and libraries to be linked, then it will extract from the archive and link into the executable each object file in the archive that provides a definition for any symbol that remains undefined up to that point in the linkage.

In so doing, definitions of unused public symbols may be redundantly linked into your program, but only if they are found in an object file (whether free-standing or a member of a library) that is not completely redundant.

If you do not want to tolerate even those potential redundancies, then a combination of compiler and linker options can eliminate them: see this answer

Community
  • 1
  • 1
Mike Kinghan
  • 46,463
  • 8
  • 124
  • 156