Gcc Inline 函數

1.      編譯時使用–Winline,讓gcc對標誌成inline但不能被展開的函數給出警告信息。

2.      Inline是一種優化,只在有優化的編譯選項中起作用,若編譯時沒使用-O選項,任何函數都不會被內聯。

3.      Inline 不能被展開的常見情況

(1)    使用了可變參數;

(2)    非局部goto語句;

(3)    對inline函數地址的引用,遞歸是特殊的一種;

(4)    Inline函數定義之前的調用語句是不會被替換展開的。

4.      常見使用情況

4.1  inline

When an inline function is not static, then the compiler must assume that there may be calls from other source files; since a global symbol can be defined only once in any program, the function must not be defined in the other source files,so the calls therein cannot be integrated. Therefore, a non-static inline functionis always compiled on its own in the usual fashion

4.2  static inline

如果對這個函數的所有調用都可以直接在調用函數中展開,而且此函數的地址沒有被引用過。gcc不會生成此函數的彙編代碼,除非你指定-fkeep-inline-functions選項。

4.3  extern inline

If you specify both inline and extern in the functiondefinition, then the definition is used only for inlining. In no case is thefunction compiled on its own, not even if you refer to its address explicitly.Such an address becomes an external reference, as if you had only declared thefunction, and had not defined it.
    函數由inline和extern同時指定,這個函數定義只會在調用中展開,即使你明確引用它的地址,gcc也不會生成此函數的彙編代碼。這個地址會被當成一個外部引用,就好像你只是聲明瞭這個函數,卻沒有定義它。
This combination of inlineand extern has almost the effect of a macro. The way to use it is to puta function definition in a header file with these keywords, and put anothercopy of the definition (lacking inline and extern) in a library file. Thedefinition in the header file will cause most calls to the function to be inlined.If any uses of the function remain, they will refer to the single copy in thelibrary.

此種情況下,能被展開的就被展開,不能被展開的如地址引用,就引用庫中的另外的拷貝。作用就是讓一個庫函數在能夠被內聯的時候儘量被內聯使用。


<注>本文源於作者按自己的思路對網上和相關書籍資料的整理歸納

發佈了44 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章