Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline functions in C++

Tags:

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

like image 654
Flash Avatar asked Aug 22 '10 09:08

Flash


2 Answers

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.

like image 195
CB Bailey Avatar answered Oct 17 '22 22:10

CB Bailey


Keep in mind that the compiler operates on a file-by-file basis, i.e. it treats each .cpp file as its own discrete unit. There is no connection between each one of them (except of course references to other functions and variables that are glued together by the linker).

If you inline something, and if the compiler decides to take you by the word (remember that inline is a hint, which means the compiler can choose to ignore you), it will embed the function into the code of whichever other block is calling it, so there will be no function that the linker can point other .cpp files two.

As an example:

File a.cpp:

void func1() {
  // code...
}

This will create an object file (like a.obj) which contains the code for func1 in a way that others can call it. The linker will be able to tell other .cpp files to go there.

File b.cpp:

void func2() {
  func1();
}

This will create b.obj which contains func2 with a function call to func1. The code has no idea what func1 does, it just has a branch here and asks the linker to put the right address in once everything has been compiled.

This is all nice an good, but if a.cpp only had an inlined version of func1, the linker will have nothing to give func2() to.

like image 27
EboMike Avatar answered Oct 17 '22 21:10

EboMike