Why is the -ObjC linker flag needed to link categories in static libraries? (LLVM)

隐身守侯 提交于 2019-11-30 08:57:47

The linker treats static libraries like a big old collection of random pieces from which it will draw individual pieces to fulfill any symbol requests from the rest of the link unit.

I.e. if the main program calls _foo and _foo only appears in the static library, then _foo, along with any dependent symbols, will be dragged in.

However, when you call a method in a category, there is no specific symbol reference due to the dynamism of Objective-C.

The -ObjC flag tells the linker that, because of this, it should grab all categories from the static library and drop 'em into the main binary.


It is a bit confusing and the assumption is that the compiler should be smarter about this (and, assuredly, it should give assistance at the dev tools level). It is important to remember a few things:

  • Anything declared in a header file is pretty much lost by the time the linker rolls around. Symbols are created by compilation units, not by header files. Header files pretty much generate a promise that a symbol will be concretely created later or fulfilled by the link, but cannot create a symbol in and of themselves (or else everyone compilation unit -- every .o -- would end up with a copy of the symbol and hilarity would ensue at link time).

  • Objective-C is fully dynamic. When you say [(id)foo bar];, the only requirement is that bar is defined somewhere prior. Doesn't matter if it is actually implemented at all (until runtime anyway).

  • Categories don't have to have corresponding @implementations; a category can be used to declare that methods might exist and, in fact, prior to adding @optional to @protocol, it was common to use a category on NSObject (ewwwwww) with no @implementation to say "Hey, this optional method might exist at runtime".

  • Compilation and linking are completely separate processes. Compilation is all about expanding the code and turning it into libraries of executable bytes. Linking is all about taking those libraries and putting them together into something that can actually be run, including resolving all the dependencies between libraries. The compiler doesn't really know about how something might be linked and the linker doesn't have any information about where things (that didn't yield hard symbols) might have been defined.

End result?

The linker doesn't have enough information to resolve the dependencies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!