1

I have a file main.cpp

#include <iostream>
#include "Cc.h"

int main ()
{
  abc::Cc objc; //namespace abc
  objc.function();
  std::cout<<"hello world"<<std::endl;
  return 0;
}

File Cc.h has :

//definition of function() is in Cc.cpp
#pragma once
#include "B.h"

namespace abc
{
  xyz::B obj; //namespace xyz
  class Cc
{
 public:
  Cc(void);
  void function();
  ~Cc(void);
};
}


//definition of function() is here in Cc.h
#if 0
namespace abc
{
xyz::B obj;
class Cc
{
public:
  Cc(void) {}
  void function() {
   obj.functionb();
   std::cout<<"inside the function of class cc"<<std::endl;}
   ~Cc(void) {}
};
#endif

File B.h has :

//definition of functionb() is in B.cpp
#pragma once
#include <iostream>
namespace xyz
{
    class B
    {
     public:
      B(void);
  void functionb();

    virtual ~B(void);
    };
}

B.cpp has

#include "B.h"
namespace xyz
{

    B::B(void)
    {
    }
    void B::functionb()
    {
   std::cout<<"inside the function of class B"<<std::endl;
    }

    B::~B(void)
    {
    }
}

If the definition for function() is there in "Cc.h" then the code runs fine. But if the function definition is in Cc.cpp, it gives error

main.obj : error LNK2005: "class xyz::B abc::obj" (?obj@abc@@3VB@xyz@@A) already defined in Cc.obj C:\Users\20033172\Documents\Visual Studio 2010\Projects\namespaceTest\Debug\namespaceTest.exe : fatal error LNK1169: one or more multiply defined symbols found

Can anyone tell how is this Linking process happening? Any help is appreciated.

Rakib
  • 7,435
  • 7
  • 29
  • 45
learner
  • 45
  • 2
  • 8

1 Answers1

1

This line in Cc.h is both a declaration and a definition. It gets defined in all the compilation units that include Cc.h.

xyz::B obj; //namespace xyz

Changing it to:

extern xyz::B obj; //namespace xyz

should fix the linking error.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • after the above suggested modification , compilation leads to the following error *Cc.obj : error LNK2001: unresolved external symbol "class xyz::B abc::obj" (?obj@abc@@3VB@xyz@@A)* – learner May 28 '14 at 13:04
  • What are the contents of Cc.cc? – R Sahu May 28 '14 at 15:18