Static vs inline for functions implemented in header files

The way I think of inline in C ++ relates to binding / scope definition. I put it in the same basket with extern and static for global objects.

Typically, for a function implemented in the header file, my solution would be to make it static:

 // In Foo.h static void foo() { // Do stuff... } 

However, I believe that this is also fair and does not seem to violate ODR:

 // In Foo.h inline void foo() { // Do stuff... } 

What are the semantic differences between the two? Also, I'm not quite sure which areas of the C ++ standard will explain the exact differences, or if it's just undefined and the differences lie in the implementation.

+4
c ++
source share
3 answers

inline conveys exactly what you want: "please suppress the ODR rule for this function so that each translation unit can (and should) provide its own copy of the function definition."

Then the compiler either performs the built-in function calls, or combines the definitions of functions from different TUs (so that the resulting function exists once in the executable file).

static , on the other hand, tells the compiler to generate a function in each translation unit where it is defined, and simply not share it. Thus, you get an arbitrary number of technically separate functions that exist in the resulting executable file.

In a nutshell, if you use static , then using the address in different translation units will return different addresses (because you tell the compiler to create a function in each TU), but if you use inline , they will show the same address ( because you define one function and just tell the compiler to combine many definitions together).

+10
source share

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

+5
source share

In many cases, you will not notice the difference, because these days compilers and linkers are pretty smart. However, an inline function should behave as if it were a regular function. The static function in the header will be compiled into each source file that includes it, so there will be many copies of it.

Basically, it doesn't really matter, but there are several ways to do this. The built-in function has one address. Static functions will have a different address in each translation unit.

Static-local variables: using the built-in string there will be one. With static functions, there will be a unique copy of each static local variable for each translation unit that includes this function.

+2
source share

All Articles