C++: what is the proper way of declaring function prototype in anonymous namespace?

1.5k views Asked by At

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?

1

There are 1 answers

0
StenSoft On BEST ANSWER

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()
    {
        …
    }
}