致命错误LNK1169:在c ++中找到一个或多个多重定义的符号

时间:2014-05-28 05:23:46

标签: c++ linker-errors

我有一个文件main.cpp

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

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

文件Cc.h有:

//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

文件B.h有:

//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有

#include "B.h"
namespace xyz
{

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

    B::~B(void)
    {
    }
}

如果函数()的定义在“Cc.h”中,那么代码运行正常。但是如果函数定义在Cc.cpp中,则会给出错误

main.obj:错误LNK2005:“类xyz :: B abc :: obj”(?obj @ abc @@ 3VB @ xyz @@ A)已在Cc.obj中定义 C:\ Users \ 20033172 \ Documents \ Visual Studio 2010 \ Projects \ namespaceTest \ Debug \ namespaceTest.exe:致命错误LNK1169:找到一个或多个多重定义的符号

有人能说出这个链接过程是怎么发生的吗? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

Cc.h中的这一行既是声明也是定义。它在包含Cc.h的所有编译单元中定义。

xyz::B obj; //namespace xyz

将其更改为:

extern xyz::B obj; //namespace xyz

应修复链接错误。