3

Error:

CMakeFiles\Final_Project_2nd.dir/objects.a(Tab.cpp.obj): In function `Z8Type2IntNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE':
C:/Users/Andrea/CLionProjects/Final_Project_2nd/Utils.hpp:37: multiple definition of `Type2Int(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
CMakeFiles\Final_Project_2nd.dir/objects.a(main.cpp.obj):C:/Users/Andrea/CLionProjects/Final_Project_2nd/Utils.hpp:37: first defined here

I've created a header Utils.hpp with two enums and two functions and I included it wherever I needed to use these things:

enum Types {
    OptionInt,
    OptionFloat,
    [...]
    OptionInvalid
};
enum Commands {
    CommandCreate = OptionInvalid + 1,
    CommandDrop,
    [...]
    CommandInvalid
};
Types Type2Int(string type){
    if(type == "int") return OptionInt;
    if(type == "float") return OptionFloat;
    [...]
    return OptionInvalid;
}
Commands Command2Int(string command){
    if(command == "CREATE") return CommandCreate;
    if(command == "DROP") return CommandDrop;
    [...]
    return CommandInvalid;
}
John Bardeen
  • 105
  • 7
  • 1
    declare these functions as `inline` – Hrisip Jun 15 '20 at 08:29
  • Why is my question already down-voted 25 seconds after I've posted it? Is there anything wrong with it? I didn't "make an effort" to make it work because I've literally no idea why that error is there – John Bardeen Jun 15 '20 at 08:32
  • I guess people get frustrated when a person doesn't know the fundamentals. This one has to do with ODR(One Definition Rule) – Hrisip Jun 15 '20 at 08:34
  • Thank you @Adler it worked! I've never used `inline` before, why is it necessary here? – John Bardeen Jun 15 '20 at 08:35
  • 1
    You've declared a function in a header file. So you will get this error whenever you include this header in several compilation units(.cpp files). To make things right, you need to either declare as `inline` or define these functions in a compilation unit – Hrisip Jun 15 '20 at 08:37
  • @Adler I've never been taught this topic... I've only followed 2 courses at university, but I'm studying electrical engineering... If there's a "noob" section I'll join it – John Bardeen Jun 15 '20 at 08:38
  • just take a respectable book on C++ and go with it. To be pragmatic, I would recommend 'A Tour of C++'(by Bjarne Stroustrup) – Hrisip Jun 15 '20 at 08:40
  • Thanks, I'll certainly do it after the exam period! Since this is not my "main" subject I may be inappropriate or I may use an imprecise language, I get it, but I'm trying my best for now. – John Bardeen Jun 15 '20 at 08:49

1 Answers1

2

You are defining the function in the header, that's the problem. multiple definition in header file

The inline solution is fine, in alternative you can keep the declaration in the hpp file and implement it in a separate cpp file - which is the most 'standard' solution.

farbiondriven
  • 2,450
  • 2
  • 15
  • 31