Search code examples
c++functionc++11scopenamespaces

C++11 namespace scoping with functions


Right now, I am coding a complex project in c++. I've simplified the example, where in a namespace I'm defining two functions, that both need each other.

namespace Example {
   void foo()
   {
      bar();
   }

   void bar()
   {
      foo();
   }
}

Is there any way to fix my issue, without separating the functions from the namespace?


Solution

  • You can forward-declare inside a namespace exactly the same way you can do it at global namespace scope:

    namespace Example {
       void bar();
    
       void foo()
       {
          bar();
       }
    
       void bar()
       {
          foo();
       }
    }
    

    However, as for any function, if these are functions defined in a header file shared between multiple translation units, then you would need to mark them inline. If they are functions declared and defined only in one .cpp meaning in one translation unit, then they should probably be marked static, so that other functions with the same name can be declared in other translation units without name clash and consequent ODR violations and UB.

    Also, you can open and close a namespace as often as you want and in as many files and translation units as you want. E.g.

    namespace Example {
        void foo();
        void bar();
    }
    

    in a header file and

    #include<header.h>
    
    namespace Example {
        void foo()
        {
           bar();
        }
    
        void bar()
        {
           foo();
        }
    }
    

    in a corresponding .cpp is also fine.