简体   繁体   中英

C++ Namespace error : not a member of namespace

I've declared a variable in a namespace as extern in a header file, say ah 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. 
}

Inside ah you declare a variable as extern, so the definition will have to appear in a cpp file (translation unit to be correct):

 // a.h
 namespace example1
 { 
     extern int a; 
 }

So here is the file where you define the variable:

 // a.cpp
 #include"a.h"
 namespace example1
 { 
    int a = 10; 
 }

Now you use the variable a defined in a.cpp

// b.cpp
#include"a.h"
namespace example2
{ 
   void f(){
    a = 5; // error : 'a' not declared in this scope. 
   }
}

And indeed, a is in namespace example1, a is not qualified name and compiler fails. (Compiler look for a in namespace ::example2 and its parent the global namespace )

Second example:

 // b.cpp
 #include"a.h"
 using namespace example1;
 namespace example2
 { 
   void f(){
     a = 5; 
   }
 }

This should compile because now a is visible at the global namespace scope. But if you still see an error now, it shall be at the linkage phase. Before building the executable, the linker is going to look for a definition of a so you must also give him the result of compiling a.cpp. For example if you use GCC, compile with this command line c++ b.cpp a.cpp .

This also applies to this example:

  // b.cpp
 #include"a.h"
 namespace example2
 { 
    void f(){
       example1::a = 5; 
    }
 }

Here you perform qualified name look up, so it should compile. If error occurs this should be at link time as described in the previous example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM