-1

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 compile first case? I don't want have function definition in *.h file.

senfen
  • 877
  • 5
  • 21

1 Answers1

2

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.

villintehaspam
  • 8,540
  • 6
  • 45
  • 76
  • 1
    Not quite. Two unnamed namespaces within the same translation unit are treated more or less as having the same name, that is unique from any other translation unit. So you can have a declaration in an unnamed namespace at the top of a `.cpp` file, and a definition in another at the bottom, and they will match up, but not across two files. – BoBTFish Nov 01 '13 at 22:53