3

If I declare it in .h in obvious way:

namespace <named_namespace> {
    namespace {
        …
        <type> <function>(<parameters>);
        …
    }
}

and put its implementation in .cpp, a compilation error will occur:

'<type> <named_namespace>::{anonymous}::<function>(<parameters>)' should have been declared inside <named_namespace>

Is it possible to avoid this error without putting the function's implementation in the single file? Currently I use keyword static instead, but it produces multiply annoying warnings:

'<type> <named_namespace>::<function>(<parameters>)' declared 'static' but never defined

which, as I've understood, can be disabled only by keeping function in a single file (header or source).

Cross-compiler solution is welcome (if any).

Or maybe splitting the header file into 'public' and 'private' parts is more efficient?

Vercetti
  • 437
  • 1
  • 6
  • 17
  • 1
    Why putting this function in header if it is *private* ? – Jarod42 Jun 16 '15 at 11:37
  • Why is it declared in an anonymous namespace? As the compiler says, it shouldn't be. What are you trying to accomplish? – molbdnilo Jun 16 '15 at 11:38
  • 1
    The purpose of an unnamed namespace is to avoid visibility from other translation units, so it would be a nonsense to declare it. See this SO question : http://stackoverflow.com/questions/357404/why-are-unnamed-namespaces-used-and-what-are-their-benefits – Nielk Jun 16 '15 at 11:39
  • This looks like an [xy problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), what are you trying to do? Putting anonymous namespaces in header files almost never makes sense. Similarly for static functions. Why do you want to declare it in multiple files if it is only defined and only usable from one file? – Jonathan Wakely Jun 16 '15 at 11:54
  • Well, I lack static class funtionality in C++ so I've tried to implement it via namespaces. Now I see that it's impossible. – Vercetti Jun 16 '15 at 12:27

1 Answers1

6

You cannot have anonymous namespace that works across translation units therefore putting anonymous namespace in .h won't work as you expect. In each translation unit (.cpp), that namespace is assigned a different, unique name.

Separated declaration and definition is possible but only inside that namespace:

namespace {
    void func();
}

…

namespace {
    void func()
    {
        …
    }
}
StenSoft
  • 9,369
  • 25
  • 30