views:

46

answers:

2

I tend to put the body of smaller functions right into the header file foo.h, not into the separate implementation file foo.cc, because then the compiler can always see those functions completely and decide to inline them.

Example:

// File "foo.h":
struct Foo { 
  // ...   
  int GetCount() const { return count_; }
};

Now any code that uses Foo sees the whole GetCount implementation and can decide to inline it.

Is that good practice? If so, do you put slightly larger function definitions into the header file as well?

A: 

It's good practice, yes. I think, practically speaking, for this scenario, as long as you understand the behaviors, then you can feel free to inline your functions as you wish. Note that the compiler will make the ultimate decision about inlining though.

tenfour
+2  A: 

Modern compilers have link time optimization, so it is not necessary anymore to have the code available in the header for a function to get inlined. Hence I would say it would be a better practice to just mark the declaration as inline, but put the definition in the cpp.

inflagranti
Marking the declaration as `inline` wouldn't do anything, the compiler will consider it anyway. The only use for `inline` now is to change ODR rules.
GMan
I didn't say it will do anything to the compiler. But it marks your intention of hoping to have them inlined, which would be the equivalent of the mentioned practice of putting the definition in the header.
inflagranti
Nice! But for `gcc`, it seems that feature is only included in gcc 4.5 or higher (http://gcc.gnu.org/gcc-4.5/changes.html). There it can be activated by the special flag `-flto`.
@dehmann: Then best practice would be to leave in the source file. The current version will not inline it but when you upgrade your compiler you get an automatic speed increase.
Martin York