Using same namespace in multiple files

I am trying to use a namespace in separately compiled files. The individual compiles work fine, but the final link does not. Here is some simple code that has this problem:

File main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

void a();
void b();

int main()
{
   a();
   b();
}


File a.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

#include "nn.h"

using namespace std;
using namespace nn;

void a()
{
   i++;
   cout << "i = " << i << endl;
}


File b.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

#include "nn.h"

using namespace std;
using namespace nn;

void b()
{
   i++;
   cout << "i = " << i << endl;
}


File nn.h
1
2
3
namespace nn {
   int i = 5;
};


Here is the compilation sequence
1
2
3
4
5
6
7
$ g++ -c main.cpp
$ g++ -c a.cpp
$ g++ -c b.cpp
$ g++ main.o a.o b.o
b.o(.data+0x0): multiple definition of `nn::i'
a.o(.data+0x0): first defined here
collect2: ld returned 1 exit status 


How can I get the compiler to recognize that I am referring to one and only one namespace? Thanks.
The initialization is the definition of the variable. Only declare global variables in headers. Define them in .cpps:
1
2
3
4
5
6
7
8
//header:
extern T var;
//.cpp:
T var;
//or
T var(/*...*/); //Note: writing T var(); will not produce the expected result.
//or
T var=/*...*/;
Based on the last response, I have tried several ways to get the code to compile. For example, I changed the assignment in nn.h to int i;, then tried extern int i;, and a few others. All of these ways failed. Can you provide a modification to my code that will get it to compile? (I could put all the source in one file, but that is NOT an acceptable solution for what I am trying to do.) Thanks.
Topic archived. No new replies allowed.