Linker errors with namespaces?

Started by
2 comments, last by Sheep 21 years, 8 months ago
Hello. I am having some desperate problems with namespaces. Lets say that I have one file, file1.h. In that file, I define something like this:
  
namespace A
{
  int variable;

  class C
  {
    C(int var) {}
    ...
  };
}; 

File1.cpp:

...

  
Now I have another file, file2.cpp:
  
#include "file1.h"

void SomeFunc()
{
  C mynewclass(A::variable);
}   
This generates a linker error: file1.obj : error LNK2005: "int A::variable" (?...) already defined in file2.obj. I have inclusion guards set up and everything. What is going on? Thanks.
Advertisement
Whats happening is that you've declared the variable in a header file. When this file is included in more than one source file, (remember that all the text is copied to the start of the file you include it in) the variable is declared a number of times.

You need to declare the variable in the header file as extern and then declare it once in the cpp file, ie :



      namespace A{  extern int variable;  class C  {    C(int var) {}    ...  };};     

file1.cpp

         #include "file1.h"namespace A {  int variable;};    




[edited by - RobTheBloke on July 24, 2002 8:06:20 AM]
Ahhh...OK. I didn''t think that I needed to use extern because the variables were inside of a namespace.
The namespace just changes the name, not any of the standard rules about duplicating objects and so on. See my article (end of my signature) if you don''t understand all the various issues.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions | Organising code files ]

This topic is closed to new replies.

Advertisement