I have a program composed of multiple classes, many of which refer to each other. So as per recommendations I create a prototype for each one as a header file. Any module that requires another gets an appropriate #include. The files compile but fail to link and I can't figure out why. Here's an example reduced to the minimum. First a prototype, data.h:
#ifndef DATA_H#define DATA_Hclass Data { public: int get(); void set(int); Data();};#endif
Next is the implementation file, data.cpp:
class Data { private: int content; public: int get() { return content; } void set(int value) { content = value; } Data() {}};
And finally the main program, test.cpp:
#include "data.h"int main(int argc, char* argv[]) { Data* data = new Data(); data->set(5); int n = data->get(); return 0;};
I compile with
g++ -c test.cpp data.cpp
No errors there so I link with
g++ test.o data.o
and the following errors result:
/usr/bin/ld: test.o: in function `main':test.cpp:(.text+0x2f): undefined reference to `Data::Data()'/usr/bin/ld: test.cpp:(.text+0x44): undefined reference to `Data::set(int)'/usr/bin/ld: test.cpp:(.text+0x50): undefined reference to `Data::get()'collect2: error: ld returned 1 exit status
Can anyone explain what I'm doing wrong?