The problem I have is basically the same as 'greentype' mentions at
<Link Removed>
I'm sharing variables through namespaces and a problem arises when I try to put my function definitions into a separate file.
Consider the following example, where I want to pass variable 'i', defined
in the main code, to the function a():
------------------------------
*** nn.h: ***
#ifndef _NN_H_
#define _NN_H_
namespace nn {
int i;
}
#endif
*** main.cpp ***
#include <iostream>
#include "nn.h"
using namespace std;
using namespace nn;
void a();
int main()
{
i=5;
a();
}
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
------------------------------
But now if I put the definition of a() into a separate file ...
------------------------------
*** a.cpp ***
#include <iostream>
#include "nn.h"
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
------------------------------
... then I get 'multiple definition' error when linking (g++ main.cpp
a.cpp -o main). If I make 'i' declaration in the header file 'extern' (as
suggested in other forums), I get 'undefined reference' error. I can compile when 'i' is declared as const in the header, but that's not what I want.
Any suggestions greatly appreciated.
<Link Removed>
I'm sharing variables through namespaces and a problem arises when I try to put my function definitions into a separate file.
Consider the following example, where I want to pass variable 'i', defined
in the main code, to the function a():
------------------------------
*** nn.h: ***
#ifndef _NN_H_
#define _NN_H_
namespace nn {
int i;
}
#endif
*** main.cpp ***
#include <iostream>
#include "nn.h"
using namespace std;
using namespace nn;
void a();
int main()
{
i=5;
a();
}
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
------------------------------
But now if I put the definition of a() into a separate file ...
------------------------------
*** a.cpp ***
#include <iostream>
#include "nn.h"
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
------------------------------
... then I get 'multiple definition' error when linking (g++ main.cpp
a.cpp -o main). If I make 'i' declaration in the header file 'extern' (as
suggested in other forums), I get 'undefined reference' error. I can compile when 'i' is declared as const in the header, but that's not what I want.
Any suggestions greatly appreciated.
Comment