-1

I've got a problem when declaring a class in a separate object file and then using it in the main function of another file:

main.cpp:

#include <helloclass.hpp>


using namespace std;

int main() {
    Hello hi;
    hi.hello();

    return 0;
}

helloclass.cpp:

#include <iostream>

using namespace std;

class Hello {
    public:

    void hello() {
        cout << "Hello world\n";
    }

    Hello() {}
};

helloclass.hpp:

class Hello {
    public:

    void hello();


    Hello();
};

Then I ran the following commands:

g++ -I. -c main.cpp
g++ -c helloclass.cpp
g++ -o main main.o helloclass.o

However, the last command gives the following output:

main.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `Hello::Hello()'
main.cpp:(.text+0x2b): undefined reference to `Hello::hello()'
collect2: error: ld returned 1 exit status

To me, it seems like I'm missing something pretty obvious. Does anyone know how to fix this?

asc11
  • 419
  • 3
  • 7
  • 3
    You should not try to program in C++ by trial and error. You should go get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Rakete1111 Jun 14 '17 at 17:08
  • thanks, but I've already got one. – asc11 Jun 14 '17 at 17:32

1 Answers1

1

You should not redefine the class in the separate source file. Instead include the header-file and implement the Hello::hello function (and the Hello::Hello constructor).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621