I have Qt libraries 4.8.1 for Windows (VS 2010 ultimate) with Qt Visual Studio Add-in. This is my very simple app :
#include<qobject.h>
#include<qstring.h>
#include<memory>
class MyClass : public QObject{
Q_OBJECT
public:
MyClass( const QString &text, QObject *parent = 0 ) : m_text(text) {}
public slots:
void setText( const QString &text );
signals:
void textChanged( const QString& );
private:
QString m_text;
};
void MyClass::setText( const QString &text ){
if( m_text == text ) return;
m_text = text;
emit textChanged( m_text );
}
int main(int argc, char *argv[]){
std::shared_ptr<MyClass> a(new MyClass("foo"));
std::shared_ptr<MyClass> b(new MyClass("bar"));
QObject::connect( a.get(), SIGNAL(textChanged(const QString&)),
b.get(), SLOT(setText(const QString&)) );
a->setText("changed");
}
Errors I get related to unresolved externals : Error 6 error LNK2001:
unresolved external symbol “public: virtual int __thiscall
MyClass::qt_metacall(enum QMetaObject::Call,int,void * *)”
(?qt_metacall@MyClass@@UAEHW4Call@QMetaObject@@HPAPAX@Z)Error 4 error LNK2001: unresolved external symbol “public: virtual
struct QMetaObject const * __thiscall MyClass::metaObject(void)const ”
(?metaObject@MyClass@@UBEPBUQMetaObject@@XZ)Error 5 error LNK2001: unresolved external symbol “public: virtual
void * __thiscall MyClass::qt_metacast(char const *)”
(?qt_metacast@MyClass@@UAEPAXPBD@Z)Error 3 error LNK2019: unresolved external symbol “protected: void
__thiscall MyClass::textChanged(class QString const &)” (?textChanged@MyClass@@IAEXABVQString@@@Z) referenced in function
“public: void __thiscall MyClass::setText(class QString const &)”
(?setText@MyClass@@QAEXABVQString@@@Z)
and two warnings :
Warning 1 warning MSB8017: A circular dependency has been detected
while executing custom build commands for item
“GeneratedFiles\Debug\main.moc”. This may cause incremental build to
work incorrectly.Warning 2 warning : No resources in
‘C:\Users\Anonymous\documents\visual studio
2010\Projects\qtWorld\qtWorld\qtworld.qrc’.
I didn’t use any qmake / nmake . They ain’t required when you get latest Qt Visual Studio Add-in 1.1.11 (even Intellisense recognizes the keywords slots: signals:), right?
Now my questions :
- I heard many errors are resolved by just rebuilding the whole solution , why is that ?
- Please explain why I get these errors in deep and their possible solutions.
p.s please be good at explanation, don’t be rep whorer
If you have QObject class defined in cpp file then you should also include moc for that file.
For example your MyClass is defined in main.cpp then you should add
to end of your main.cpp file.
Thanks to @Tomma for providing the unexplained answer 😛
Explanation why above code didn’t work :
However, the moc is typically applied to header files only. Since your class definition is part of the main program file, the IDE does not recognize it.
Thanks to @koahnig for providing nice explanation