内联关键字与标题定义 [英] Inline keyword vs header definition

查看:119
本文介绍了内联关键字与标题定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个函数之前使用inline关键字和在头文件中声明整个函数有什么区别?



所以...

  int whatever(){return 4; } 

vs



.h: / p>

  inline int whatever(); 

.cpp:

  inline int myClass :: whatever()
{
return 4;
}

这样做:

  inline int whatever(){return 4; } 


解决方案

有几个方面:



语言




  • 当函数标有 inline 关键字,那么它的定义应该在TU中可用或者程序是错误的。

  • 在类定义中定义的任何函数隐式标记为 inline

  • <
  • 模板函数(非完全专用)获得与 inline 个。


编译器行为 b


  • 标记为 inline 的函数将在每个目标文件中作为弱符号发出,

  • 而编译器实际上内联调用(即,在使用点复制/粘贴代码,而不是执行常规函数调用)。完全由编译器自行决定。关键字的存在可能或不会影响决策,但最好是一个提示。



链接器行为




  • 弱符号合并在一起,在最终库中出现一次。一个好的链接器可以检查多个定义是否一致,但这不是必需的。


What's the difference between using the inline keyword before a function and just declaring the whole function in the header?

so...

int whatever() { return 4; }

vs

.h:

inline int whatever();

.cpp:

inline int myClass::whatever()
{
    return 4;
}

for that matter, what does this do:

inline int whatever() { return 4; }

解决方案

There are several facets:

Language

  • When a function is marked with the inline keyword, then its definition should be available in the TU or the program is ill-formed.
  • Any function defined right in the class definition is implicitly marked inline.
  • A function marked inline (implicitly or explicitly) may be defined in several TUs (respecting the ODR), whereas it is not the case for regular functions.
  • Template functions (not fully specialized) get the same treatment as inline ones.

Compiler behavior

  • A function marked inline will be emitted as a weak symbol in each object file where it is necessary, this may increase their size (look up template bloat).
  • Whereas the compiler actually inlines the call (ie, copy/paste the code at the point of use instead of performing a regular function call) is entirely at the compiler's discretion. The presence of the keyword may, or not, influence the decision but it is, at best, a hint.

Linker behavior

  • Weak symbols are merged together to have a single occurrence in the final library. A good linker could check that the multiple definitions concur but this is not required.

这篇关于内联关键字与标题定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆