This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Understanging the use of inline funtions


Hello,

I have a couple of questions regarding the inline keyword using g++ in
general.

First some example code to work with:

inline_main.cpp:
01: #include <iostream>
02: #include <cstdlib>
03: 
04: #include "inline_test.h"
05: 
06: int main(void)
07: {
08:   Foo foo;
09: 
10:   std::cout << foo.GetX() << std::endl;
11: 
12:   return EXIT_SUCCESS;
13: }

inline_test.h:
01: class Foo
02: {
03: public:
04:   Foo();
05: 
06:   int GetX() const;
07: 
08: private:
09:   int x;
10: };

inline_test.cpp:
01: #include "inline_test.h"
02: 
03: Foo::Foo()
04:   : x(5)
05: {}
06: 
07: int Foo::GetX() const
08: {
09:   return this->x;
10: }

That compiles perfectly using 
g++ -Wall -o inline inline_test.cpp inline_main.cpp

Now I found different statements in discussions and online artciles
saying
1. The inline keyword is just a hint. The compiler decides if it uses
it or not.
2. C'tors and d'tors are always automatically inlined.
3. GCC does not use the inline keyword but has its own ideas about
inlining function calls.
4. GCC does inlining not below -O3 or the explizit activation using
-finline-functions
4. Everything defined in a header file is inlined.

Some of them are contradictory and I'd like to know, what really
happens using GCC.

If I change inline_test.h:06 to
inline int GetX() const;
I would expect that the code still works, after reading the statements
above. But I get a warning:
inline_test.h:6: warning: inline function âint Foo::GetX() constâ used
but never defined

Seems perfectly correct to me, because the definition of GetX is not
known at a point its code should be inlined. It was alreay compiled
into object code when compiling inline_test.cpp.
On the other hand, that would mean, that the compiler _always_ has to
obey to the inline keyword if the definition is given in a cpp file.
And that also means to me, that there is no way to _not_ inline code if
it is given in the header file, because there won't be any object code
from comiling a cpp file and the compiler can not know if the code
generated from the definition in the header file can be shared between
different object files. It can compile the function to objectcode and
use that more than once within one object if there are multiple calls.

All that renders the whole inline-is-just-a-hint-discussion very hard
to understand (if not to say: inconstistent) to me. So I hope I can get
some explanations from you, as you implemented the whole thing at least
for GCC, which I use. :-)

Regards,
Tobias


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]