问题描述
我无法理解以下行为:一个标头具有一些基本类型,另一个标头在多个函数中使用这些类型.之后我开始根据我定义的类型和函数构建类.如果我留下以下签名,则在函数头中:
I can't make sense of the following behavior: one header with some basic types, and another header in which I use these types in several functions. Afterward I started constructing classes based on my defined types and functions. In the function header if I leave the following signature:
void whateverFunction(parameters)
链接器指出whateverFunction有多个定义.现在,如果将其更改为:
The linker points out that there are multiple definitions of whateverFunction. Now if change it to:
inline void whateverFunction(parameters)
链接问题消失了,所有编译和链接都很好.我对内联的了解是,它用它的代码替换了每个函数调用,而不是它很暗,所以我的问题是:
the linkage problem is gone and all compiles and links well. What I know concerning inline is that it replaces every function call with it's code other than that it's a pretty dark, so my question is:
链接器如何处理 C++ 中的内联函数?
推荐答案
当header中的函数不是内联的,那么这个函数的多个定义(例如在多个翻译单元中)是违反ODR规则的.
When the function in the header is not inline, then multiple definitions of this function (e.g. in multiple translation units) is a violation of ODR rules.
内联函数默认具有外部链接.因此,由于 ODR 规则(如下所示),这样的多重定义(例如在多个翻译单元中)是可以的:
Inline functions by default have external linkage. Hence, as a consequence of ODR rules (given below), such multiple definitions (e.g. in multiple translation units) are Okay:
$3.2/5-可以有多个类类型的定义(第 9 条),枚举类型 (7.2),内联外联功能(7.1.2),类模板(第 14 条),非静态函数模板(14.5.6),类模板的静态数据成员(14.5.1.3),类的成员函数模板 (14.5.1.1) 或模板一些模板的专业化未指定参数 (14.7,14.5.5) 在程序中,前提是每个定义出现在不同的翻译单位,并提供定义满足以下条件要求.给定这样一个实体命名 D 定义在多个翻译单元,然后
$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
——D 的每个定义应包括具有相同的令牌序列;和 [...]
— each definition of D shall consist of the same sequence of tokens; and [...]
链接器如何处理内联函数几乎是实现级别的细节.只要知道实现在 ODR 规则的限制范围内接受这种多重定义就足够了
How the linker treats inline functions is a pretty much implementation level detail. Suffice it to know that the implementation accepts such mulitple defintions within the limitations of ODR rules
请注意,如果 header 中的函数声明更改为static inline....",则内联函数显式具有内部链接,并且每个翻译单元都有自己的静态内联函数副本.
Note that if the function declaration in header is changed to 'static inline....', then the inline function explicitly has internal linkage and each translation unit has it's own copy of the static inline function.
这篇关于内联函数联动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!