namespaces question

Greetings C++ gurus,

I am experimenting with namespaces, and I would like to make a namespace packaged in a separate file so that it can be included and used as desired without touching the namespace source code. I found that I can do this if the namespace is in a header file which is included into the main .cxx source file (below). However the problem I am having with this is that I believe only function declarations should be included in header files, not function definitions. What is the proper way to package into a separate file the implementation of namespace functions?

Thanks!

-Maxim-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//-file nmsp3a.hxx
#include <iostream>
#include <string>

using namespace std;

namespace allnmsp{

  namespace nmsp1{
    void func(string str)
    {
      cout << str << " -from nmsp1" << endl;
    }
  }

  namespace nmsp2{
    void func(string str)
    {
      cout << str << " -from nmsp2" << endl;
    }
  }

}



//-file nmsp3b.cxx
#include "nmsp3a.hxx"

int main(void)
{
  allnmsp::nmsp1::func("Hello world!");
  allnmsp::nmsp2::func("Hello world!");

}

For this case, have three files.

Header file allnmsp.hxx, in which namespace members are declared:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//////////////  file allnmsp.h ////////////////

#ifndef ALLNMSP_HXX_INCLUDED
#define ALLNMSP_HXX_INCLUDED

#include <string>

namespace allnmsp
{

    namespace nmsp1
    {
        void func( std::string str ) ;
        extern int value ;
    }

    namespace nmsp2
    {
        void func( std::string str ) ;
        extern int value ;
    }
}

#endif // ALLNMSP_HXX_INCLUDED 


Implementation file allnmsp.cxx, in which namespace members are defined:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//////////////  file allnmsp.cxx ////////////////

#include "allnmsp.hxx"
#include <iostream>

namespace allnmsp
{
    namespace nmsp1
    {
        void func( std::string str )
        {
            std::cout << str << " -from allnmsp::nmsp1: value == " << value << '\n' ;
        }

        int value = 23 ;
    }
}

void allnmsp::nmsp2::func( std::string str )
{
    std::cout << str << " -from allnmsp::nmsp2: value == " << value << '\n' ;
}

int allnmsp::nmsp2::value = 555 ;


Implementation file main.cxx
1
2
3
4
5
6
7
8
9
10
//////////////  file main.cxx ////////////////

#include <iostream>
#include "allnmsp.hxx"

int main()
{
  allnmsp::nmsp1::func( "Hello world!" );
  allnmsp::nmsp2::func( "Hello world!" );
}
Great, it works! Thanks!
Topic archived. No new replies allowed.