2
votes

I am kinda new and getting some really weird errors in my c++ code. As best as i can tell, they are due to multiple inclusion errors.

I have the following files

CardBase.h

#include <string>
#include <vector>
#include <map>

class Class1 {
    string someString;
    vector<type> someVector;
    map<type,type> someMap;
    type someMethod (param);
}

CardBase.cpp

#include "StringParser.cpp"

someType Class1::someMethod (param){
    // Use splitAtChar()
}

StringParser.cpp

#include <string>
#include <vector>

someType splitAtChar(){
    ...
}

This produces two errors in VS code:

LNK2005 "class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > __cdecl splitAtChar(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,char)" (?splitAtChar@@YA?AV?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@D@Z) already defined in CardBase.obj

and

one or more multiply defined symbols found

2
Why does this happen? When the compiler finds #include "file", it replaces the include with a copy of whatever is in file.user4581301
Does this answer your question? One or more multiply defined symbols foundStaceyGirl

2 Answers

4
votes

Yep, don't include one cpp file in another. Use header files.

CardBase.cpp

#include "StringParser.h"

someType Class1::someMethod (param){
    // Use splitAtChar()
}

StringParser.cpp

#include "StringParser.h"
#include <string>
#include <vector>

someType splitAtChar(){
    ...
}

StringParser.h

#ifndef STRING_PARSER_H
#define STRING_PARSER_H

someType splitAtChar();

#endif

This is basic stuff, your C++ book should explain how to organise your code.

2
votes

In your CardBase.cpp

#include "StringParser.cpp"

someType Class1::someMethod (param){
    // Use splitAtChar()
}

You are including a .cpp file. If you additionally compile this, then you are defining splitAtChar() twice, and hence the errors.