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
542 views
in Technique[技术] by (71.8m points)

redefinition - Re-definitions of functions while including files in C++ (error LNK2005)

I'm new to C++ and I have a basic doubt.
I'm creating a french verb conjugating application.
I have two files, a Conjugator.cpp file and an ErVerbs.cpp file. I want to keep the bulk of my functions in the ErVerbs source file and use the conjugator file to use these functions.

Here are a few code snippets:

Conjugator.cpp

#include <iostream>
#include <string>
#include "Variables.h"
#include "ErVerbs.cpp"
#include "IrVerbs.cpp"
#include "ReVerbs.cpp"
using namespace std;

void check()
{
    if (verb.substr(len - 2, len) == "er")
        erVerbs();
    else if (verb.substr(len - 2, len) == "ir")
        irVerbs(); 
    else if (verb.substr(len - 2, len) == "re")
        reVerbs();
}
int main()
{
    cout << "Enter verb : ";
    getline(cin, verb);
    cout << "Enter tense : ";
    getline(cin, tense);
    len = verb.length(); 
    check();
}

ErVerbs.cpp

#include <iostream>
#include <string>
using namespace std;

void erVerbs()
{
    cout << "er Verb"; cin.get(); 
}

Similarly, I have three other such .cpp source files with similar functions.

When I build the program, I get an error that each of the methods I'm using has been defined already.

1>ErVerbs.obj : error LNK2005: "void __cdecl erVerbs(void)" (?erVerbs@@YAXXZ) already  defined in Conjugator.obj
1>ErVerbs.obj : error LNK2005: "void __cdecl erVerbs(void)" (?erVerbs@@$$FYAXXZ) already defined in Conjugator.obj
1>IrVerbs.obj : error LNK2005: "void __cdecl irVerbs(void)" (?irVerbs@@YAXXZ) already defined in Conjugator.obj
1>IrVerbs.obj : error LNK2005: "void __cdecl irVerbs(void)" (?irVerbs@@$$FYAXXZ) already defined in Conjugator.obj
1>ReVerbs.obj : error LNK2005: "void __cdecl reVerbs(void)" (?reVerbs@@YAXXZ) already defined in Conjugator.obj
1>ReVerbs.obj : error LNK2005: "void __cdecl reVerbs(void)" (?reVerbs@@$$FYAXXZ) already defined in Conjugator.obj

I'd be extremely grateful if someone could tell me how to save functions in separate source files and #include them in one source files and use their functions without re-definition errors.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should never include *.cpp files. Delete following

#include "ErVerbs.cpp"
#include "IrVerbs.cpp"
#include "ReVerbs.cpp"

Create erVerbs.h with following content:

void erVerbs();

and include it in Conjugator.cpp

#include "ErVerbs.h"

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

2.1m questions

2.1m answers

60 comments

57.0k users

...