c++namespacesglobal-namespacenon-member-functions

Namespaces and free functions


I have a free function, foo, defined in a namespace N. The header for foo is in the global include search path so anyone can call it by including foo.h.

foo calls another local, free function, foo1, which is defined in foo.cpp.

// foo.h
namespace N
{
    void foo();
} 


// foo.cpp
#include "foo.h"

namespace
{
    // declare in the unnamed namespace?
    void foo1()
    {
        // do some stuff
    }
}

namespace N
{
    // declare in namespace N?
    void foo1()
    {
        // do some stuff
    }

    void foo()
    {
        foo1();
    }

} // N

Should I put foo1 in the unnamed namespace or in namespace N? Or doesn't it matter?

UPDATE

I want to limit the scope of foo1 to foo.cpp.


Solution

  • That's not a global namespace, but an anonymous one. Defining it there will only allow foo1 to be used in that translation unit, so you can't declare it somewhere else and use it afterwards.

    This will effectively limit its scope to foo.cpp. If that's your intention, declare it in an anonymous namespace.

    If you want to be able to use it from outside, declare it in the global namespace or N (global namespace means you just leave it out of a namespace) - depending on where it makes sense.

    void global_foo();
    
    namespace
    {
       void internal_linkage_foo();
    }
    
    namespace X
    {
       void foo_from_x();
    }