C++ – Inline Functions Explained [Duplicate]

c++

Hii ,

I am a novice in C++. I did read about inline functions and understood them right. But this site says that "We get an 'unresolved external' error if we write the definition of an inline function in one .cpp file and call it from another file….why is that so … ?
This can be done for normal functions right…Please correct me if i am wrong …

Thanks

Best Answer

It's a language requirement. inline means that you may have the function defined in more than one translation unit but the definitions must be identical and that you must have a definition in every translation unit that uses the function.

Those are the rules. The rules allow (but don't require) the compiler to expand the code for the inline function at each call site and omit emitting a callable function version.

This is different from non-inline functions which must only be defined once across all translation units. This is the usual "one definition rule" which applies to most entities in C++.

inline doesn't change the linkage of a function. inline functions have, by default, external linkage so if you use a static variable inside an inline function the implementation must ensure that there is only one copy of that variable in the program.

Related Question