Search code examples
c++multiple-definition-error

Multple c++ files causes "multiple definition" error?


I'm using multiple C++ files in one project for the first time. Both have need to include a protected (#ifndef) header file. However, when I do that, I get a multiple definition error.

What I have is two one .cpp file that calls the header directly, and one indirectly (Another include includes it) and then two other header files that include it.

So what do I need to do to get rid of the error?

ERROR:

obj\Debug\main.o||In function Z14sortLibQtyTest4BookS_':| [PATH]\miscFuncs.h|16|multiple definition ofsortLibQtyTest(Book, Book)'

CODE:

bool sortLibQtyTest(Book a, Book b){ return a.getQty() > b.getQty(); }

It should be mentioned that this isn't the only function giving me problems, probably more than ten are, and some aren't so short and sweet. Also, the functions are needed in multiple files.


Solution

  • You have two options to solve this multiple definition problem: Mark the method inline, or put the definition in a .cpp file.

    1) Mark the method inline:

    // Foo.h
    
    inline bool foo(int i) { return i = 42; }
    

    2) Put the definition in a .cpp file:

    // Foo.h
    
    inline bool foo(int i); // declaration
    
    // Foo.cpp
    bool foo(int i) { return i = 42; } // definition
    

    Whether the method is actually inlined by the compiler in the first case is irrelevant here: inline allows you to define a non-member function in a header file without breaking the one definition rule.