Error trying to separate the class in .h, .cpp

advertisements

This is a minimal program that I made to understand this problem better.

ADT.h

#ifndef ADT_H
#define ADT_H

class ADT {
public:
      void print();
};

#endif

ADT.cpp

#include <iostream>
#include "ADT.h"

using namespace std;

void ADT::print()
{
   cout << "This program works." << endl;
}

testADT.cpp

#include <iostream>
#include "ADT.h"

using namespace std;

int main(void)
{
   ADT sa;
   sa.print();

   return 0;
}

I compiled it with the vim/minGW compiler my school provided me like so:

g++ testADT.cpp

Which produced the following error:

C:\Users\King\AppData\Local\Tempcc6eoWAP.o:testADT.cpp(.text+0x15 reference to 'ADT::print()'
collect2.exe error: ld returned 1 exit status

Can you explain this error message and indicate the error in my code?


You didn't post the error, but I see that you're missing the semicolon after void print()in the header.

EDIT: That's a linker error. Each source file should be compiled into an object file; then the object files linked:

g++ -c -oADT.o ADT.cpp
g++ -c -otestADT.o testADT.cpp
g++ -oADT ADT.o testADT.o

You can also do it in one line as in michaeltang's answer, but then you can't recompile the sources individually (the 2 step method scales better).