Search code examples
c++namespacesforward-declaration

Forward declaration in namespace


Consider the following scenario:

"A.cpp":

void fun() { std::cout << "fun() global\n"; }

"B.cpp":

namespace N
{
    void f()
    {
        std::cout << "f() in N\n";
        
        void fun(); // forward declaration
        fun();
    }
}

When N::f(); is called from some other file (say "C.cpp"), the compiler throws an "undefined symbol" error for fun().

How to fix this without making any changes to "A.cpp"?


Solution

  • How to fix this without making any changes to "A.cpp"?

    You need to forward declare fun in global namespace instead of inside namespace N. This can be done by moving the declaration void fun(); to outside N as shown below:

    B.cpp

    void fun(); //this is a forward declaration in global namespace 
    namespace N
    {
        void f()
        {
            std::cout << "f() in N\n";
            
            //no declaration needed here
            fun();
        }
    }
    

    Working demo