Inside General.h

#ifndef GENERAL
#define GENERAL
namespace counternamespace{
    int upperbound;
    int lowerbound;
}
#endif
Inside Analyzer.h

#ifndef ANALYZER
#define ANALYZER
#include"General.h"

class Analyzer
{
public :
     int var ;
     int func();
};
#endif
Inside Test.h

#ifndef TEST
#define TEST
#include"Analyzer.h" //Error
class Test2
{
public:
    Test2(void);

public:
    ~Test2(void);
};
#endif 

In the above code when I don't add Analyzer inside Test.h everything is working fine. But after adding its showing the following linker error.

1>Test2.obj : error LNK2005: "int counternamespace::lowerbound" (?lowerbound@counternamespace@@3HA) already defined in Analyzer.obj
2>Test2.obj : error LNK2005: "int counternamespace::upperbound" (?upperbound@counternamespace@@3HA) already defined in Analyzer.obj

I have added the #ifndef/#endif. Then where I am doing the mistakd? Can anyone please let me know?

gdeneral.h is declaring two variables and that header file is included in both analyzer.h and test.h. The same variables can't be declared more than once or you get that link error.

The work around is to use the extern keyword in general.h and then declare the same variables again but without extern in one of the *.cpp files

#ifndef GENERAL
#define GENERAL
namespace counternamespace{
    extern int upperbound;
    extern int lowerbound;
}
#endif

I followed the below things .

    1-Declare namespace inside General.h as you mentioned above .
    2-wrote - using namespace counternamespace inside General.cpp .
    3-Define the variable as below upperbound = 12 and lowerbound = 6 inside General.cpp .
    4-Include General.h inside Analyzer.h  .
    5-wrote - using namespace counternamespace inside Analyzer.cpp .
    6-use the upperbound and lowerbound inside Analyzer.cpp as below upperbound = 24 , lowerbound = 12 . 


    After doing the above things its still giving me the linker error  .

Can you please suggest what to do ?

Edited 3 Years Ago by vikuseth

Inside General.h
#ifndef GENERAL
#define GENERAL
namespace counternamespace{
   extern int upperbound;
   extern int lowerbound;
}
#endif
Inside General.cpp
#include"General.h"
using namespace counternamespace ;
int upperbound = 12;
int lowerbound = 24 ;

Inside Analyzer.h
#ifndef ANALYZER
#define ANALYZER
class Analyzer
{
public:
    Analyzer(void);
    ~Analyzer(void);
};
#endif 
Inside Analyzer.cpp
#include"Analyzer.h"
#include"General.h"
using namespace counternamespace ;
Analyzezr::Analyzer(){
cout<<upperbound;
}

The above one shows the below linker error
error LNK2001: unresolved external symbol "int counternamespace::upperbound" (?upperbound@counternamespace@@3HA)

Edited 3 Years Ago by vikuseth

This is what you want in the General.cpp file, you need to identify the namespace. Dp the same with lowerbound.

int counternamespace::upperbound = 12;

Edited 3 Years Ago by Ancient Dragon

This question has already been answered. Start a new discussion instead.