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

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

问题描述

背景

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

I have a project named PersonLibrary which has two files.

  1. Person.h
  2. Person.cpp

这个库产生一个静态库文件.另一个项目是 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 定义了 SetName 函数.当我尝试使用 TestProject 中的 SetPersonName 时,我得到 error LNK2005: already defined.这是我的使用方法

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. 静态在这里有什么不同?
  3. 这个问题的适当解决方案是什么?

谢谢

推荐答案

你要么必须

  • SetPersonName 的定义移动到 .cpp 文件,编译并链接到生成的目标
  • 使 SetPersonName 内联
  • 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. only available to the translation unit it is included in. 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天全站免登陆