📅 2010-Aug-26 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, header, inline, static, warning ⬩ 📚 Archive
A colleague handed some C++ code to integrate which had static functions in its header file like this:
// Foo.h
static void FooFun()
{ /***/ }
In every .cpp
file that includes Foo.h
, a static FooFun()
definition is compiled in. But, if you are compiling code at Warning Level 4 (/W4), then for every .cpp
file where FooFun()
is not invoked, the following warning is produced:
Main.cpp Foo.h(1): warning C4505: 'FooFun' : unreferenced local function has been removed
Due to some constraints, my colleague was not interested in moving the FooFun()
definition into the Foo.cpp
source file and exposing only the FooFun()
declaration in Foo.h
.
FooFun()
cannot be defined as a normal non-static function in the header file Foo.h
, since that would lead to linker errors that FooFun()
is already defined in another .cpp
file:Main.obj : error LNK2005: "void __cdecl FooFun(void)" (?FooFun@@YAXXZ) already defined in Joe.obj
FooFun()
as a static function in a class:// Foo.h
class Foo
{
public:
static void FooFun()
{ /***/ }
};
The header file can be included in all .cpp
files with no problems. The function can be invoked as Foo::FooFun()
in other .cpp
files and there is no compiler warning.
// Foo.h
static inline void FooFun()
{ /***/ }
Inclusion of this function definition causes no problems, and invocation of the function causes it to be inlined, thus leaving no symbols behind for linker errors. Note however, that it comes with the baggage of inline, so it should be used only for tiny function bodies.