Archived

This topic is now archived and is closed to further replies.

Linker errors with namespaces?

This topic is 5619 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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 ]

Share this post


Link to post
Share on other sites