c++ - 内联函数联动

标签 c++ function inline

我无法理解以下行为:一个 header 具有一些基本类型,而另一个 header 中我在多个函数中使用了这些类型。之后,我开始根据我定义的类型和函数构建类。如果我留下以下签名,则在函数头中:

void whateverFunction(parameters)

链接器指出,whateverFunction 有多个定义。现在如果将其更改为:

inline void whateverFunction(parameters)

链接问题消失了,所有编译和链接都很好。我所知道的关于 inline 的是,它用它的代码替换了每个函数调用,而不是它非常黑暗,所以我的问题是:

链接器如何处理 C++ 中的内联函数?

最佳答案

当 header 中的函数不是内联函数时,该函数的多个定义(例如在多个翻译单元中)是违反 ODR 规则的。

默认情况下内联函数具有外部链接。因此,由于 ODR 规则(如下所示),这样的多个定义(例如在多个翻译单元中)是可以的:

$3.2/5- "There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

— each definition of D shall consist of the same sequence of tokens; and [...]

链接器如何处理内联函数几乎是实现级别的细节。只要知道实现在 ODR 规则的限制范围内接受这样的多重定义就足够了

请注意,如果标题中的函数声明更改为“静态内联...”,则内联函数显式具有内部链接,并且每个翻译单元都有自己的静态内联函数拷贝。

关于c++ - 内联函数联动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4193639/

相关文章:

c++ - 如何在 R 中进行内联 C++ 函数调用?

c++ - 如果在内联函数中使用alloca在堆栈上分配了一个变量,那么在内联函数返回后它的引用是否有效?

c++ - C2977 : 'std::tuple' : too many template arguments (MSVC11)

c++ - 没有 Visual Studio,其他人如何运行我的 SFML/C++ 项目?

c++ - 为什么这个函数没有返回预期的值

c++ - 我应该在 C++ 中使用异常说明符吗?

mysql - 带参数的函数查询

c++ - 如何从 gluUnProject 重新定位近平面和远平面以考虑相机位置和角度?

c++ - gdb 不会执行二进制操作

c - C 中的内联函数与宏——开销(内存/速度)是多少?