Some ideas:
- One possible legitimate use I can think of is when you want to make a function available without creating a symbol with external linkage and polluting the external namespace. (But then you could just use an obscure prefixed name like
mylib123__foobar
, and #define foobar mylib123__foobar
in the header file, so this one seems a little iffy.)
- You want certain functionality to be available purely through the header file, without requiring the user to link a library/object files. I could see this being a real motivation when providing a 'library' that's almost nothing but data structures and a few trivial pieces of code to manipulate them. In fact if the data structures are not opaque and meant to be accessed directly by the application, putting functions for use with them in the same header file (versus in a library) greatly reduces the risk of breaking things if/when you change the data structures.
Perhaps the function is merely a wrapper for an external function, and the way the wrapper works might depend on compile-time options in the calling compilation unit. For example:
static int foobar(int x)
{
return real_foobar(COMPILETIME_PARAMETER, x);
}
You might say just use macros, but what if foobar
needs to be called via a function pointer for the intended usage?
With that having been said...
In reality, the main reason people put static
functions in header files is usually based on some 10-years-outdated notion that it will improve performance, by permitting the compiler to inline the function or whatnot. Most people who do this have not done any measurement. Since modern compilers can compile the whole program as a unit if asked, and this theoretically results in a lot more possibilities for optimization, and since it's a questionable optimization to begin with, I'm really skeptical of placement of functions in headers for performance purposes.
This criticism especially applies the OP's example of "large" static functions in header files. There's almost no way a large function could benefit from inlining unless a constant argument value allows the compiler to eliminate 90% of the code or something. (For a real-world example of this extreme case, see some of the crazy inline function/macro definitions used in libavcodec
. :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…