Jump to content
  • Advertisement

Archived

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

Sheep

Linker errors with namespaces?

This topic is 5987 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
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]

Share this post


Link to post
Share on other sites
Ahhh...OK. I didn''t think that I needed to use extern because the variables were inside of a namespace.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!