2

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Why does this happen? When the compiler finds `#include "file"`, it replaces the include with a copy of whatever is in file. – user4581301 Mar 24 '20 at 18:28
  • Does this answer your question? [One or more multiply defined symbols found](https://stackoverflow.com/questions/6469849/one-or-more-multiply-defined-symbols-found) –  Mar 26 '20 at 17:48

2 Answers2

4

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.

john
  • 85,011
  • 4
  • 57
  • 81
2

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.

cigien
  • 57,834
  • 11
  • 73
  • 112