Mam kod:
#include
#include
using namespace std;
class MyClass {
int mProperty;
public:
inline void setProperty(int property);
inline int getProperty();
};
inline void MyClass::setProperty(int property)
{
mProperty = property;
}
inline int MyClass::getProperty()
{
return property;
}
int main()
{
MyClass myInstance;
myInstance.setProperty(3);
cout << "value = " << myInstance.getProperty() << endl;
return 0;
}
w pliku, nazwijmy go, main.cpp. Jak widać, obydwie funkcje składowe klasy są zadeklarowane jako inline.
Robię
$ g++ main.cpp -o program
i wszystko gra.
Jednak gdy rozdzielę to na osobne pliki:
main.cpp:
#include
#include "MyClass.h"
using namespace std;
int main()
{
MyClass myInstance;
myInstance.setProperty(3);
cout << "value = " << myInstance.getProperty() << endl;
return 0;
}
MyClass.h:
#ifndef _MY_CLASS_H
#define _MY_CLASS_H
class MyClass {
int mProperty;
public:
inline void setProperty(int property);
inline int getProperty();
};
#endif
oraz MyClass.cpp:
#include "MyClass.h"
inline void MyClass::setProperty(int property)
{
mProperty = property;
}
inline int MyClass::getProperty()
{
return mProperty;
}
to na linkerze się wywala.
Kompilacja MyClass.cpp przechodzi bez problemu:
$ g++ -c MyClass.cpp -o MyClass.o
Kompilacja main.cpp daje ostrzeżenia:
$ g++ -c main.cpp -o main.o
MyClass.h:7: warning: inline function ‘void MyClass::setProperty(int)’ used but never defined
MyClass.h:8: warning: inline function ‘int MyClass::getProperty()’ used but never defined
co już jest bardzo dziwne.
Natomiast jak chcę zbudować binarkę, to dostaję błędy:
$ g++ -o program main.o MyClass.o
main.o: In function `main':
main.cpp:(.text+0x65): undefined reference to `MyClass::setProperty(int)'
main.cpp:(.text+0x6e): undefined reference to `MyClass::getProperty()'
collect2: ld returned 1 exit status
Czyli linker nie widzi funkcji...
Co jest nie tak?