#### Archived

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

# 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.

## 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 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 on other sites
Ahhh...OK. I didn''t think that I needed to use extern because the variables were inside of a namespace.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633706
• Total Posts
3013465
×