错误LNK2005:已定义 - C ++ [英] error LNK2005: already defined - C++

查看:218
本文介绍了错误LNK2005:已定义 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我有一个名为 PersonLibrary 的项目,它有两个文件。

I have a project named PersonLibrary which has two files.


  1. Person.h

  2. Person.cpp


b $ b

这个库产生一个静态库文件。另一个项目是 TestProject ,其使用 PersonLibrary (通过VS008中的项目依赖性添加)。一切工作正常,直到我添加一个非成员函数到 Person.h Person.h 看起来像

This library produces a static library file. Another project is TestProject which uses the PersonLibrary (Added though project dependencies in VS008). Everything worked fine until I added a non-member function to Person.h. Person.h looks like

class Person
{
public:
    void SetName(const std::string name);

private:
    std::string personName_;
};

void SetPersonName(Person& person,const std::string name)
{
    person.SetName(name);
}

Person.cpp / em>功能。当我尝试使用 TestProject 中的 SetPersonName 时,我会收到错误LNK2005:已定义。这是我如何使用它

Person.cpp defines SetName function. When I try to use SetPersonName from TestProject, I get error LNK2005: already defined. Here is how I used it

#include "../PersonLibrary/Person.h"
int main(int argc, char* argv[])
{
    Person person;
    SetPersonName(person, "Bill");
    return 0;
}

尝试的解决方法

1 - 我已删除 Person.cpp 并在 Person.h 中定义了整个类。错误已消失,一切正常。

1 - I have removed the Person.cpp and defined the whole class in Person.h. Error gone and everything worked.

2 - 将 SetPersonName 修饰符更改为 static 。像下面

2 - Changed the SetPersonName modifier to static. Like the below

static void SetPersonName(Person& person,const std::string name)
{
    person.SetName(name);
}

问题


  1. 为什么首先显示的代码无法按预期工作?

  2. 这里有什么区别 static

  3. 这个问题的适当解决方案是什么?

感谢

推荐答案

您必须


  • 移动 SetPersonName 定义为.cpp文件,编译并链接到生成的目标

  • make SetPersonName inline

  • move SetPersonName's definition to a .cpp file, compile and link to the resulting target
  • make SetPersonName inline

这是一个众所周知的违反一个定义规则的情况。

This is a well known case of One Definition Rule violation.

static关键字使函数的链接内部即可用于仅包含在翻译单元中。然而这隐藏了真正的问题。我建议将函数的定义移动到自己的实现文件,但保留在标题中的声明。

The static keyword makes the function's linkage internal i.e. available to the translation unit it is included in, only. This however is hiding the real problem. I'd suggest move the definition of the function to its own implementation file but keep the declaration in the header.

这篇关于错误LNK2005:已定义 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆