External Relationship Namespaces

The problem I have is basically the same as mentioning greentype http://www.cplusplus.com/forum/beginner/12458/

I use variables through namespaces, and there is a problem when I try to put my function definitions in a separate file.

Consider the following example, where I want to pass the variable 'i' defined in the main code to the a () function:


* 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 () in a separate file ...


* a.cpp *

#include <iostream>
#include "nn.h"

void a()
{
using namespace std;
using namespace nn;

i++;
cout << "i = " << i << endl;
}

... " " (g++ main.cpp a.cpp -o main). "i" "extern" (as ), "undefined reference". , "i" const , , .

.

+5
3

, i, - , .

extern . , i. extern ( extern) .

: , , . () . - , (, ) .

+12

:

namespace nn {
    extern int i;
}

"", "". :

namespace nn {
    int i = 1;
}

, , .

+10

, , i . extern, const static - , , i const. , i , , :

:

extern int i;

a.c:

int i:

main.c:

int main()
{
  i = 1; // or whatever
}

Note that I removed the namespace for clarity - the end result is the same.

+2
source

All Articles