Redefinition in C++, previous definition in header file?

6.2k views Asked by At

So I am confused. I am getting a redefinition error when trying to implement a method previously declared in a header file. I added include guards to the header and still got the same error. If someone could explain to me what I am not seeing, that would be fantastic.

In file included from main.cpp:2: ./thing.cpp:7:12: error: redefinition of 'method' int Thing::method(void) ^ ./thing.hpp:12:6: note: previous definition is here int method(void) {}; ^

--EDIT--

I am now getting the following:

duplicate symbol __ZN5Thing6methodEv in: main.o thing.o ld: 1 duplicate symbol for architecture x86_64

thing.hpp:

#ifndef THING_H
#define THING_H

class Thing {

public:
        int a;
        int b;
        char c;

        int method(void) {};
        Thing(int anA, int aB, char aC): a(anA), b(aB), c(aC) {};


};

#endif

thing.cpp

#include <iostream>
#include <stdio.h>
#include "thing.hpp"

using namespace std;

int Thing::method(void)
{
        return 5;

}

main.cpp

#include <iostream>
#include "thing.cpp"

using namespace std;

Thing* thing = new Thing(5,5,'c');

int main(int argc, char ** argv)
{
        cout << thing->method() <<endl;

}
2

There are 2 answers

0
Jonathan Potter On BEST ANSWER

In your header file you have:

int method(void) {};

That's an inline definition, not a declaration. The {} is actually providing the (albeit empty) function body to the compiler. Remove the {} if you want to define the function in another file.

Additionally, you have #include "thing.cpp" rather than #include "thing.hpp" at the top of your main.cpp file.

0
Paul R On

In main.cpp you need to change:

#include "thing.cpp"

to:

#include "thing.hpp"