0

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};

}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Tmforshaw
  • 3
  • 2
  • That makes sense, is it best practice to just declare and define namespaces in header files? Or should I avoid using a namespace in this scenario – Tmforshaw Oct 29 '20 at 21:06

2 Answers2

1

This

namespace foo {

    int array[5];

}

is a definition of the array.

On the other hand, this declaration

extern int foo::array;

is present in the global namespace instead of the namespace foo. That is the namespace foo was not yet declared and you may not use the qualified name foo::array.

To declare the array in the header use the storage specifier extern.

namespace foo {

    extern int array[5];

}

And then in the cpp file you can write for example

int foo::array[5] = {0, 1, 2, 3, 4, 5};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Same way as in global namespace:

// .h
namespace foo {
    extern int array[5];
}
// .cpp
namespace foo {
    int array[5] = {1, 2, 3, 4, 5};
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Thank you! I feel like a noob – Tmforshaw Oct 29 '20 at 21:12
  • In the `.cpp` file, you can alternatively use `int foo::array[5] = {1, 2, 3, 4, 5};` without using another `namespace {}` block. But if you have other things being defined in the same namespace, the block makes sense to use. – Remy Lebeau Oct 29 '20 at 21:34