Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

linker - error LNK2005: already defined - C++

Background

I have a project named PersonLibrary which has two files.

  1. Person.h
  2. Person.cpp

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 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;
}

Workarounds tried

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

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

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

Questions

  1. Why the code shown first is not working as I expected?
  2. What difference static made here?
  3. What is the approapriate solution for this problem?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You either have to

  • 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...