Search code examples
c++multiple-inclusions

Multiply defined symbols (C++)


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


Solution

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