簡體   English   中英

extern inline 聲明如何導致代碼生成?

[英]How does extern inline declaration cause code generation?

我從這個鏈接中引用這些行: 沒有“靜態”或“外部”的“內聯”在 C99 中有用嗎?

要在 c99 中進行內聯工作,我們需要執行以下操作:

非外部“內聯”定義位於 header 中(但不一定會導致任何代碼生成),而“外部內聯”聲明位於 .c 文件中,實際上會導致生成代碼。

上述行為受到質疑,但我找不到答案。

看起來C的設計師當時很高。 上述規則如何運作? 在所有其他C樣式編碼definition goes in headerdeclaration goes in source file 但是在這里它是倒退的,並且declaration causes code generation

您是說“函數定義應該 go 到翻譯單元”......是的,但是內聯function 應該可以在另一個翻譯單元中內聯。 並且 C 編譯器通常不會從其他翻譯單元中尋找內聯代碼,而是將單獨的翻譯單元編譯成單獨的 object 文件,只有 linker 會看到整個程序。

Back in times the solution for this would be to define a function in a header file with static (note it is a definition in a header file,), and hope that the compiler would be smart enough to inline the function. 但是愚蠢的編譯器會在每個翻譯單元中生成一個單獨的 static function,而不是內聯任何內容,從而導致性能不佳和浪費memory

Now with inline and extern inline it means that a function defined as inline foo is supposed to be the same function throughout the program - you can take the function pointer of it in any translation unit and you will get the same function pointer.

在任何地方你看到inline void foo(int bar) {... }它同樣是一個 function 定義。 但是只有在整個程序的一個翻譯單元中才會有extern inline void foo(int bar); 這將導致帶有外部鏈接的 function 出現在該文件中。 這有一個很好的特性,它使遺留工具鏈(鏈接器等)能夠完全忽略內聯關鍵字行為,他們只看到一個 function 有一個符號foo在那個 object 文件中。

最后,您不需要與外部定義的定義相同的 function 定義 - 它可以是不同的 - 只是不要包含與 Z099FB995346F31C749F6E40EDB0 完全不同的 Z099FB995346F31C749F6E40EDB0 定義的inline function 定義

inline int foo(void) {
    puts("Hello from an inlined function");
}

extern inline int foo(void) {
    puts("Hello from an external function using a completely different algorithm"
         " here that results in more code bloat but offsets the fact that the" 
         " function call to this definition was not inlined");
}

但是很高興 C 允許您擁有相同的定義而無需重復自己!

更清楚地說, extern聲明觸發了 function 的外部定義的生成,而不是它導致生成代碼。

只要翻譯單元中 function 的所有聲明都是inline而沒有extern ,編譯器只提供內聯實現,根據 C 2018 6.7.4 7:

…如果翻譯單元中 function 的所有文件 scope 聲明都包含inline extern說明符,則該翻譯單元中的定義是內聯定義 內聯定義不提供 function 的外部定義,...

因此,當您添加一個extern聲明時,該規則中的條件不再滿足——不再存在只有inline聲明而沒有extern的情況。 這提示編譯器在它生成的代碼中包含一個外部非內聯實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM