error LNK2005: already defined - C++(错误 LNK2005:已定义 - C++)
问题描述
背景
我有一个名为 PersonLibrary 的项目,它有两个文件.
I have a project named PersonLibrary which has two files.
- Person.h
- 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);
}
问题
- 为什么首先显示的代码没有按预期工作?
- 静态在这里有什么不同?
- 这个问题的适当解决方案是什么?
谢谢
推荐答案
你要么必须
- 将
SetPersonName的定义移动到 .cpp 文件,编译并链接到生成的目标 - 使
SetPersonName内联
- move
SetPersonName's definition to a .cpp file, compile and link to the resulting target - make
SetPersonNameinline
这是一个众所周知的违反单一定义规则的案例.
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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:错误 LNK2005:已定义 - C++
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
