I have declared the below namespace in sample.h
// namespace with identifier
namespace N1
{
int b = 80;
}
sample1.cpp use the above namespace declaration
#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 use 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 below 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 resolve and how “namespace std” implemented to avoid this problem ?
Include guards will work only during compile time, but the error is at link time. This is because the sample.h is included in both compilation units and a variable
N1::bis created in both.If you really want a variable (not a
const) you have to declare it asexternin the header, and create a memory location for it in a separate compilation unit: