I have 3 files Test.h , Test.cpp and main.cpp
Test.h
#ifndef Test_H
#define Test_H
namespace v
{
int g = 9;;
}
class namespce
{
public:
namespce(void);
public:
~namespce(void);
};
#endif
Test.cpp
#include "Test.h"
namespce::namespce(void)
{
}
namespce::~namespce(void)
{
}
Main.cpp
#include <iostream>
using namespace std;
#include "Test.h"
//#include "namespce.h"
int main ()
{
return 0;
}
during building it gives the following error ..
1>namespce.obj : error LNK2005: "int v::g" (?g@v@@3HA) already defined in main.obj
1>C:\Users\E543925\Documents\Visual Studio 2005\Projects\viku\Debug\viku.exe : fatal error LNK1169: one or more multiply defined symbols found
kindly help as soon as possible ..
This is a definition:
namespace v
{
int g = 9;
}
that gets duplicated in main.obj and test.obj due to the #include "Test.h" in each of the .cpp files. The include guard #ifndef Test_H only prevents multiple inclusions in a single translation unit.
Change to:
namespace v
{
extern int g; // This is now a declaration and extern tells the compiler
// that there is definition for g somewhere else.
}
and add the following to the Test.cpp:
namespace v
{
int g = 9; // This is now the ONLY definition of 'g', in test.obj.
}
You want just one instance of g accessed by everyone?
In the header, use
extern int g; // declaration
in Test.cpp, put
int v::g = 9; //definition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With