I was reading ODR and as the rule says "In the entire program, an object or non-inline function cannot have more than one definition"
and I tried the following...
file1.cpp
#include <iostream>
using namespace std;
inline int func1(void){ return 5; }
inline int func2(void){ return 6; }
inline int func3(void){ return 7; }
int sum(void);
int main(int argc, char *argv[])
{
cout << func1() << endl;
cout << func2() << endl;
cout << func3() << endl;
cout << sum() << endl;
return 0;
}
file2.cpp
inline int func1(void) { return 5; }
inline int func2(void) { return 6; }
inline int func3(void) { return 7; }
int sum(void) { return func1() + func2() + func3(); }
It worked as the rule says. I can have multiple definition of inline functions.
- What is the difference between non-inline function linkage and inline function linkage?
- How the linker differentiate between these two?
Making a function
inline
does two things (the second point is more relevant to your question):It is a suggestion by the programmer to the compiler, to make calls to this function fast, possibly by doing inline expansion. Roughly, inline expansion is similar to treating the inline function like a macro, expanding each call to it, by the code of its body. This is a suggestion - the compiler may not (and sometimes cannot) perform various optimizations like that.
It specifies the scope of the function to be that of a translation unit. So, if an
inline
function appears infoo.cpp
(either because it was written in it, or because it#include
s a header in which it was written, in which case the preprocessor basically makes it so). Now you compilefoo.cpp
, and possibly also some otherbar.cpp
which also contains aninline
function with the same signature (possibly the exact same one; probably due to both#include
ing the same header). When the linker links the two object files, it will not be considered a violation of the ODR, as theinline
directive made each copy of the file local to its translation unit (the object file created by compiling it, effectively). This is not a suggestion, it is binding.It is not coincidental that these two things go together. The most common case is for an
inline
function to appear in a header#include
d by several source files, probably because the programmer wanted to request fast inline expansion. This requires the translation-unit locality rule, though, so that linker errors shouldn't arise.