我有 Qt libraries 4.8.1 for Windows (VS 2010 ultimate) 和 Qt Visual Studio 插件。这是我非常简单的应用程序:
#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)
和两个警告:
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'.
我没有使用任何 qmake/nmake 。当您获得最新的 Qt Visual Studio 插件 1.1.11 时不需要它们(甚至 Intellisense 也能识别关键字 slots:
signals:
),对吧?
现在我的问题:
- 我听说很多错误都可以通过重建整个解决方案来解决,这是为什么呢?
- 请解释为什么我会遇到这些错误及其可能的解决方案。
p.s请大家好好解释,不要做妓女
最佳答案
如果您在 cpp 文件中定义了 QObject 类,那么您还应该为该文件包含 moc。 例如你的 MyClass 是在 main.cpp 中定义的,那么你应该添加
#include "main.moc"
到您的 main.cpp 文件的末尾。
感谢@Tomma 提供无法解释的答案:P
解释为什么上面的代码不起作用:
但是,moc 通常只应用于头文件。由于您的类定义是主程序文件的一部分,因此 IDE 无法识别它。
感谢@koahnig 提供很好的解释
关于c++ - 构建 qt 解决方案时 Unresolved external 问题和一些警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11950493/