I try do that:
file.h
namespace {
void fun();
const bool nevermind = Register( fun );
}
file.cpp
namespace {
void fun() {
do_some_job();
}
}
Having linking error. Function void fun() is not found by linker.
If I try do that:
file.h
namespace {
void fun() {
do_some_job();
}
const bool nevermind = Register( fun );
}
all goes ok.
How do I compile the first case? I don't want to have the function definition in header file.
The purpose of anonymous namespaces is to prevent you from using that function anywhere else. As such, there is little point in having it being defined in a header. I would assume that whenever you add an anonymous namespace, the compiler actually treats it as a namespace with a gibberish unique name. So when you add another anonymous namespace it is not the same namespace.
Also see comment by BoBTFish below that clarifies this a bit.