首先,要說明一下Other Linker Flags到底是用來幹嘛的。說白了,就是ld命令除了默認參數外的其他參數。ld命令實現的是連結器的工作,詳細說明可以在終端man ld查看。

如果有人不清楚連結器是什麼東西的話,我可以作個簡單的說明。

一個程式從簡單易讀的代碼到可執行檔往往要經歷以下步驟:

原始程式碼 > 前置處理器 > 編譯器 > 彙編器 > 機器碼 > 連結器 > 可執行檔

原始檔案經過一系列處理以後,會生成對應的.obj檔,然後一個專案必然會有許多.obj檔,並且這些檔之間會有各種各樣的聯繫,例如函式呼叫。連結器做的事就是把這些目的檔案和所用的一些庫連結在一起形成一個完整的可執行檔。

為什麼會閃退

蘋果官方Q&A上有這麼一段話:

The "selector not recognized" runtime exception occurs due to an issue between the implementation of standard UNIX static libraries, the linker and the dynamic nature of Objective-C. Objective-C does not define linker symbols for each function (or method, in Objective-C) - instead, linker symbols are only generated for each class. If you extend a pre-existing class with categories, the linker does not know to associate the object code of the core class implementation and the category implementation. This prevents objects created in the resulting application from responding to a selector that is defined in the category.

翻譯過來,大概意思就是Objective-C的連結器並不會為每個方法建立符號表,而是僅僅為類建立了符號表。這樣的話,如果靜態程式庫中定義了已存在的一個類的分類,連結器就會以為這個類已經存在,不會把分類和核心類的代碼合起來。這樣的話,在最後的可執行檔中,就會缺少分類裡的代碼,這樣函式呼叫就失敗了。

解決方法

解決方法在背景那塊我就提到了,就是在Other Linker Flags里加上所需的參數,用到的參數一般有以下3個:

  • -ObjC
  • -all_load
  • -force_load

下面來說說每個參數存在的意義和具體做的事情。

首先是-ObjC,一般這個參數足夠解決前面提到的問題,蘋果官方說明如下:

This flag causes the linker to load every object file in the library that defines an Objective-C class or category. While this option will typically result in a larger executable (due to additional object code loaded into the application), it will allow the successful creation of effective Objective-C static libraries that contain categories on existing classes.

簡單說來,加了這個參數後,連結器就會把靜態程式庫中所有的Objective-C類和分類都載入到最後的可執行檔中,雖然這樣可能會因為載入了很多不必要的檔而導致可執行檔變大,但是這個參數很好地解決了我們所遇到的問題。但是事實真的是這樣的嗎?

如果-ObjC參數真的這麼有效,那麼事情就會簡單多了。

Important: For 64-bit and iPhone OS applications, there is a linker bug that prevents -ObjC from loading objects files from static libraries that contain only categories and no classes. The workaround is to use the -allload or -forceload flags.

當靜態程式庫中只有分類而沒有類的時候,-ObjC參數就會失效了。這時候,就需要使用-all_load或者-force_load了。

-all_load會讓連結器把所有找到的目的檔案都載入到可執行檔中,但是千萬不要隨便使用這個參數!假如你使用了不止一個靜態程式庫檔,然後又使用了這個參數,那麼你很有可能會遇到ld: duplicate symbol錯誤,因為不同的庫檔裡面可能會有相同的目的檔案,所以建議在遇到-ObjC失效的情況下使用-force_load參數。

-force_load所做的事情跟-all_load其實是一樣的,但是-force_load需要指定要進行全部載入的庫檔的路徑,這樣的話,你就只是完全載入了一個庫檔,不影響其餘庫檔的按需載入。

arrow
arrow

    狼翔月影 發表在 痞客邦 留言(0) 人氣()