根据一个定义规则 (ODR) 我不能有一个函数
void function()
{
}
在一个可执行文件中多次定义 - 链接器将反对。但是,内联函数会忽略 ODR:
inline void function()
{
}
可以在头文件中定义,该头文件将#included 到多个 .cpp 文件中,因此当生成的 .obj 文件链接在一起时,链接器会发现该函数有多个实例,并有意忽略它。它假设它是完全相同的函数并且只使用其中一个实例。由于保留了程序行为,因此无人关心。
但如果由于任何原因,use of preprocessor included ,这些实例恰好有不同的实现,链接器将再次选择其中一个函数,而开发人员在彻底测试他的程序之前甚至不知道选择了哪一个。
当链接器选择其中一个函数并且它们恰好有不同的实现分类时,后一种情况如何?这是未定义的行为还是任何其他情况?
最佳答案
是的,它是用于具有外部链接的内联函数的 UB(我认为这就是 OP 的意图)。
$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.5), 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.4) 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
最后同段说不满足这些要求导致UB
关于c++ - 将内联函数的不同实现链接到一个可执行文件中的情况如何分类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4143946/