"Inline" function

I may just have trouble understanding the exact definition, but is an "Inline" function anything special?
Or is it just calling a function within another function?
As far as I am aware it tells the compiler to put the entire body of that code where you call it.

Ex

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

inline void hello( void )
{
    std::cout << "Hello" << std::endl;
}

int main()
{
    hello(); //It is really putting the body here - std::cout << "Hello" << std::endl;
}


Basically it just copies what is in the body of it and pastes it into where it was being called.




inline function is a function you can define more than once:

Try it: without inline:
~$ cat file1.cpp
void f() {}
int main() {}
~$ cat file2.cpp
void f() {}
~$ g++ -o test file1.cpp file2.cpp
/tmp/ccv8KRBv.o: In function `f()':
file2.cpp:(.text+0x0): multiple definition of `f()'


with inline:
~$ cat file1.cpp
inline void f() {}
int main() {}
~$ cat file2.cpp
inline void f() {}
~$ g++ -o test file1.cpp file2.cpp
~$
As Cubbi said, an inline function may be safely defined in multiple source files ("translation units") so long as the definitions are all the same.

What giblit mentions is actually a misunderstanding - whether or not a function is inline doesn't matter, the compiler always makes the final decision whether to inline a function call or not.
The C++ standard does say that the inline keyword is to indicate that you'd prefer that a function is inlined (if possible.)

In this sense it doesn't appear to of much use these days as modern compilers seem happy enough to inline things whenever they feel it's appropriate without being asked (and, of course, ignore the request if they don't like it.)

I assume that old-fashioned compilers did have to be asked to inline functions, and that the relaxation of the one-definition rule was made to allow this to work.

Andy
Last edited on
Topic archived. No new replies allowed.