static vs inline for functions implemented in header files

inline conveys exactly what you want: "please suppress the ODR (One Definition Rule) for this function, so that each translation unit can (and must) supply its own copy of the function's definition".

The compiler will then either inline calls to the function, or merge together the function definitions from different TU's (so that the resulting function exists once in the executable).

static, on the other hand, tells the compiler to generate the function in every translation unit where it is defined, and just not share it. So you end up with an arbitrary number of technically separate functions existing in the resulting executable.

In a nutshell, if you use static, then taking the address of the function in different translation units will return different addresses (because you're telling the compiler to generate a function in each TU), but if you use inline, they'll show the same address (because you're defining one function, and just telling the compiler to merge the many definitions together).


In many cases you will not notice a difference because compilers and linkers are pretty smart these days. However, an inline function must behave as-if it was a regular function. A static function in a header will get compiled into every source file which includes it - so there will be lots of copies of it.

Mostly, this doesn't matter much, but there are a few ways it does. An inline function has one address. Static functions will have a different address in each translation unit.

Static-local variables: WIth the inline, there will be a single copy of them. With static-functions, there will be a unique copy of each static-local variable for each translation unit that includes that function.


The main difference is what happens with any static locals in the function -- if the function is static then each compilation unit will have its own copy of the static locals distinct from any other compilation unit. If the function is inline, there will only be one (set of) static local(s) shared by all compilation units.

Tags:

C++