Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"using namespace" for defining global functions

When defining class member functions in the source file, we can use using namespace ns1::ns2::...::nsx to avoid having to fully qualify function names.

E.g.

// Header file - foo.hpp
namespace ns1::ns2 {
    class FooClass {
        void fooMethod();
    }
}

// Source file - foo.cpp
#include "foo.hpp"
using namespace ns1::ns2;
void FooClass::fooMethod() {
    // do something
}

However, I recently got into a confusion when trying to define a global function.

See the following example.

// Header file - bar.hpp
namespace ns1::ns2{
    void barFunction();  // <-- compile error: undefined reference
}

// Source file - bar.cpp
#include "bar.hpp"
using namespace ns1::ns2;
void barFunction(){
    // do something
}

I was expecting the compiler to deduce the definition in bar.cpp to be the definition of ns1::ns2::barFunction defined in bar.hpp. But it doesn't do that. (Everything works fine if I use the fully qualified name in the definition).

Is this the expected behavior or am I doing something wrong?

like image 702
Anubis Avatar asked Nov 23 '25 09:11

Anubis


1 Answers

It's expected behavior.

[namespace.udir]

3 A using-directive does not add any members to the declarative region in which it appears.

This means there is no declaration for barFunction in the global namespace at the point you define it. And that makes the definition the first and only declaration of such a function (in the global namespace).

This is by design, because a using directive can often bring in way more names than expected. So not having it trample the declarative region it appears in is good.

like image 139
StoryTeller - Unslander Monica Avatar answered Nov 25 '25 22:11

StoryTeller - Unslander Monica