You, and the people here giving advice about small functions, are looking at inline
the old-fashioned way.
inline
used to mean "I want this code to run quickly, so whenever I call this function, I want you to expand it in-place to avoid the overhead of a function call."
That's a really good optimization. It's so good, in fact, that the compiler will eagerly do it even if you don't specify inline
.
The compiler is also free to not expand your inline
functions. So you really don't have to worry about how it will affect performance, because the compiler can and will ignore inline
if you use it in a stupid way.
In fact, compilers today almost always ignore your use of inline
, and just do whatever they think is best.
So, knowing that, why do people still use inline
?
There's only one reason to use inline
nowadays, and that's to work around the One Definition Rule (ODR).
In C/C++, you're only allowed to define a function once. If you do this:
int foo() { /* do something */ }
int foo() { /* do something else */ }
the compiler will complain that you've defined the same function twice.
That looks like a silly example, but it's particularly easy to do something like that when you're using #include
- if you defined your function in a header, and you #include
the same header twice, this is exactly what you're doing.
Thankfully, inline
has another use which is still valid today: if you mark a function as inline
, it forces the compiler to silence ODR issues, making it possible to define your function in a header.
In other words, inline
now means "I want to define this function in a header."
When you look at it that way, it should be clear that you should remove the inline
when moving the function into a cpp file.
For interest sake, there's a couple places where functions are implicitly made inline. One of them is in class member functions:
struct Foo {
void bar() { /* do something */ }
};
I've seen people mark functions like this inline
, but that's completely redundant. The compiler does it anyway; there's no need to worry about ODR, and there's no performance to be gained.
The other place is in templates. Since templates have to be defined in headers, they're exempt from the ODR, and inline
ing them is redundant.