Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a situation when different implementations of an inline function are linked into one executable classified?

According to One Definition Rule (ODR) I can't have a function

void function()
{
}

defined more than once in one executable - linker will object. However ODR is ignored for inline functions:

inline void function()
{
}

can be defined in a header file that will be #included into multiple .cpp files and so when resulting .obj files are linked together the linker sees that there're several instances of that function and intentionally ignores that. It assumes it is the very same function and just uses one of the instances. Since the program behavior is preserved noone cares.

But if thanks to any reason, use of preprocessor included, those instances happen to have different implementations the linker will again pick one of the functions and the developer won't even know which one is picked until he thoroughly tests his program.

How is the latter situation when the linker picks one of the functions and they happen to have different implementations classified? Is this undefined behavior or any other kind of situation?

like image 579
sharptooth Avatar asked Nov 10 '10 11:11

sharptooth


1 Answers

Yes, it is UB for inline functions with external linkage (I think that's what the OP intends).

$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

The same paragraph at the end states that failure to meet these requirements leads to UB

like image 164
Chubsdad Avatar answered Sep 22 '22 13:09

Chubsdad