Split a namespace in multiple files

Hi.
I want to create a namespace named MyNS.
Can I define it in multiple files?
I mean:

file1.h
1
2
3
4
namespace MyNS
{
   const int File1 = 0;
}

file2.h
1
2
3
4
namespace MyNS
{
   const int File2 = 1;
}

main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "file1.h"
#include "file2.h"
using namespace MyNS;

int main()
{
   std::cout << File1 << ' ' << File2 ;
}
Why you didn't try it yourself? It's a trivial problem which you can solve like in 3 minutes. Posting there took you more time!

As for your question: yes, you can.
@MiiNiPaa
If he tries this how do he know if this behaviour is standard or just specific to that compiler? C++ is not a try-and-see language. You need to know what you are doing.
Last edited on
I use GCC. does it need additional linker option?
Can I nest namespaces like this?
No need for additional linker options, or anything. This is standard C++ and will work.
closed account (zb0S216C)
majidkamali1370 wrote:
"Can I nest namespaces like this?"

A name-space can have as many name-space scopes as it wishes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace Alpha
{
    namespace Bravo
    {
        namespace Charlie
        {
            namespace Delta
            {
                int Value_( 0 );
            }
        }
    }
}

int main( )
{
    Alpha::Bravo::Charlie::Delta::Value_ = ...;
}

Wazzak
Thank you guys ;)
Topic archived. No new replies allowed.