I have the simplest code that I want to separate in three files:
- Header file: class and struct declarations. No implementations at all.
- Inline functions file: implementation of inline methods in header.
- Code file: normal C++ code for more complicated implementations.
When I was about to implement an operator[] method, I couldn’t manage to compile it. Here is a minimal example that shows the same problem:
Header (myclass.h):
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class MyClass
{
public:
MyClass(const int n);
virtual ~MyClass();
double& operator[](const int i);
double operator[](const int i) const;
void someBigMethod();
private:
double* arr;
};
#endif /* _MYCLASS_H_ */
Inline functions (myclass-inl.h):
#include "myclass.h"
inline double& MyClass::operator[](const int i) {
return arr[i];
}
inline double MyClass::operator[](const int i) const {
return arr[i];
}
Code (myclass.cpp):
#include "myclass.h"
#include "myclass-inl.h"
#include <iostream>
inline MyClass::MyClass(const int n) {
arr = new double[n];
}
inline MyClass::~MyClass() {
delete[] arr;
}
void MyClass::someBigMethod() {
std::cout << "Hello big method that is not inlined" << std::endl;
}
And finally, a main to test it all:
#include "myclass.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyClass m(123);
double x = m[1];
m[1] = 1234;
cout << "m[1]=" << m[1] << endl;
x = x + 1;
return 0;
}
void nothing() {
cout << "hello world" << endl;
}
When I compile it, it says:
main.cpp:(.text+0x1b): undefined reference to 'MyClass::MyClass(int)'
main.cpp:(.text+0x2f): undefined reference to 'MyClass::operator[](int)'
main.cpp:(.text+0x49): undefined reference to 'MyClass::operator[](int)'
main.cpp:(.text+0x65): undefined reference to 'MyClass::operator[](int)'
However, when I move the main method to the MyClass.cpp file, it works. Could you guys help me spot the problem?
Thank you.
Your main program file used to test your setup does not include the header file with the inline member functions. Since the functions are inline, they are not included in the object file produced from
myclass.cpp.The inline functions are not available to the compiler, so it thinks the calls are external; but they are also not available to the linker, since they do not generate standalone definitions anywhere else.
If you want the functions to be inline, just put them in
myclass.h.