Access to membership in C ++ namespace in different files how? How is "namespace std" implemented?

I declared the following namespace in sample.h

// namespace with identifier
namespace N1
{
    int b = 80;
}

sample1.cpp use the above namespace

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

using namespace std;
using namespace N1;

int main(void)
{
    cout << "b (in main) = " << b << endl;
      foo(); //written in sample2.cpp
      return 0;
}

sample2.cpp also uses the namespace declared in sample.h

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

using namespace std;
using namespace N1;

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

when i compiled i got the following errors

$> g++ sample1.cpp sample2.cpp
/tmp/ccB25lEF.o:(.data+0x0): multiple definition of `N1::b'
/tmp/cchLecEj.o:(.data+0x0): first defined here

Let me know how to solve and how " namespace std " is implemented to avoid this problem?

+3
source share
7 answers

, . , sample.h , N1::b .
( const), extern :

// sample.h
#ifndef N1
#define N1
namespace N1 {
    extern int b;
}
#endif

// sample.cpp
#include "sample.h"
namespace N1 {
    int b = 80;
}
+5

#ifndef.

extern :

//sample.h
namespace N1
{
    extern int b; //extern is MUST!

    //DONT WRITE : extern int b = 80;
}

.cpp :

//sample.cpp
namespace N1
{
    int b = 80;  //initialization should be here
}
+8

ifdef pragma sample.h?

+3

, #include sample.h .cpp-, b, [1].

int sample.cpp - extern int b sample.h.


[1] , , .

+3

, , . .

, (, . ) .

// sample.h
namespace N1
{
    extern int b;
}

// sample.cc
namespace N1
{
    int b = 80;
}

, , b, . , b , , const .

// sample.h
namespace N1
{
    const int b = 80;
}
+2

, :

namespace N1
{
    enum MyEnum
    {
      b = 80
    };
}

- .h, , , . " " : , ( .cpp). : , , (, N:: b) (=.cpp ).

. , , - , . : , int MyInt 40 80 : , ? , ( ) - , . .

Using enum was an easy way to avoid having to separate the declaration and definition in your case (since enum is not covered by the second version of the One Definition rule), but if you really need a (non-constant) global type int, you can achieve this as follows:

sample.h

namespace N1
{
    // The extern keyword tells the compiler that this is is only
    // a declaration and the variable is defined elsewhere.
    extern int b;
}

sample1.cpp

#include "sample.h"

namespace N1
{
    // This is the definition!
    int b = 5;
}

void foo()
{
    using namespace std;
    cout<<N1:b<<endl;
}

sample2.cpp

#include "sample.h"

// No need to define N1::b, since it was already defined in sample1.cpp.

void bar()
{
    using namespace std;
    cout<<N1:b<<endl;
}
+1
source

The program contains two variable definitions N1::b, while there must be exactly one. A variable must be declared in the header using externand defined in only one source file.

0
source

All Articles