I've declared a variable in a namespace as extern in a header file, say a.h I'm including this file in a .cpp file say a.cpp and defining that variable in the same namespace. This works fine.
Now, I'm including this header file in another .cpp file, say b.cpp and using this variable in a different namespace. This throws me the error saying variable 'a' is not declared in this scope. I include the namespace using 'using namespace' in b.cpp file. Still I get the same error. Using the expression namespace::variable in b.cpp gives the error saying variable 'a' is not a member of that namespace.
Following is the code snippets for understanding my problem.
// a.h
namespace example1
{
extern int a;
}
// a.cpp
#include"a.h"
namespace example1
{
a = 10;
}
// b.cpp
#include"a.h"
namespace example2
{
a = 5; // error : 'a' not declared in this scope.
}
// b.cpp
#include"a.h"
using namespace example1;
namespace example2
{
a = 5; // error : 'a' not declared in this scope.
}
// b.cpp
#include"a.h"
namespace example2
{
example1::a = 5; // error : 'a' not a member of example1.
}
a=10;
shall generate an error too. – Oliva=10
is not a definition. You can assign to variable only in functions. If your intent is to define a, writeint a =10;
– Oliv==
as the operator. A single=
means assignment. Also, if you declare a variable extern it needs to be declared somewhere eventually, but you failed that. Instead you have a very weird usage of namespaces scoping. – rlam12