static vs inline for functions implemented in header files

后端 未结 4 1146
心在旅途
心在旅途 2021-02-01 18:20

The way I think of inline in C++ is for linkage/scoping. I put it in the same basket with extern and static for global objects.

Ty

4条回答
  •  佛祖请我去吃肉
    2021-02-01 19:00

    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).

提交回复
热议问题