繁体   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