Partager via


Inline or Not Inline

What is inline? This keyword is mainly used to ask the compiler to inline substitution of the function body at the point of call. Like 'register', this is only a suggestion to the compiler. Modern compiler can handle inlining using advanced heuristic to get better size / performance balance without the suggestion from the developer. So most of the time, it is unnecessary to use this keyword.

Then what else? Here is the whole story of inline.

Besides the suggestion to the compiler, inline keyword will also have some side effects.

Assuming I have defined a function 'f' in header file and include the header in two different files: a.cpp and b.cpp. Like:

void f() {}

You'll get the following error when compiling (cl a.cpp b.cpp):

b.obj : error LNK2005: "void __cdecl f(void)" (?f@@YAXXZ) already defined in a.obj
a.exe : fatal error LNK1169: one or more multiply defined symbols found

However, if you change the definition of f to:

inline void f() {}

The compilation will succeed.

Here are the words from the standard:

Every program shall contain exactly one definition of every non-inline function or object that is used in that program. An inline function shall be defined in every translation unit in which it is used.

This is the fundamental difference between using or not using inline. That means inline functions can be defined multiple times in different translation unit (assuming they have exactly the same definition in every case), but it will also cause the so-called "inline-explosion" because the definition has to be duplicated.

A function defined within a class definition is an inline function. If you don't want to duplicate the definition everywhere, it is better to move the definition into a separate cpp. /LTCG can still inline it if appropriate.