asc11 asc11 -4 years ago 45
C++ Question

C++ issue with class declared in a separate object file

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:


#include <helloclass.hpp>

using namespace std;

int main() {
Hello hi;

return 0;


#include <iostream>

using namespace std;

class Hello {

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

Hello() {}


class Hello {

void 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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download