Search code examples
c++namespacesdeclarationdefinitionname-lookup

How can I forward declare an array inside a namespace in c++


I've been trying to find out how I can use namespaces properly. I want to use a namespace, but not have to define it in the header file. I am not sure how I can do this with an array inside the namespace. I either get an "already defined symbol" error, or I get told that the namespace has not been declared.

I have tried to write code like this:

//Header.h

namespace foo {
    int array[5];
}
//Source.cpp

#include "Header.h"

namespace foo {
    int array[5] = {0, 1, 2, 3, 4, 5};
}

And it returns an error.

If I try to forward-declare the namespace, like I would any other variable, it says the namespace is undefined, so I'm not sure what the correct way to achieve this is.

//Header.h

extern int foo::array;
//Source.cpp

#include "Header.h"

namespace foo {
    
    int array[5] = {0, 1, 2, 3, 4, 5};

}

Solution

  • Same way as in global namespace:

    // .h
    namespace foo {
        extern int array[5];
    }
    
    // .cpp
    namespace foo {
        int array[5] = {1, 2, 3, 4, 5};
    }