2011-11-23 36 views
6

我试着写一个简单的Qt应用程序是这样的:为什么这个简单的Qt应用程序无法链接

main.cpp中

#include <QApplication> 

class MyApp : public QApplication { 
     Q_OBJECT 
public: 
     MyApp(int argc, char* argv[]); 
}; 

MyApp::MyApp(int argc, char* argv[]) : 
     QApplication(argc,argv) { 
} 

int main(int argc, char* argv[]) { 
    MyApp app(argc,argv); 
    return app.exec(); 
} 

但是,当我试图编译和使用Qt将其链接造物主2.3.1(QT 4.7.4)我得到3 “解析外部符号” 错误:

I think they are somehow related to the MetaObjectCompiler of Qt, but I can't figure out a solution. I know it's not considered good programming style in c++ to put declarations and definitions in one file, but that's not the point here. In my opinion it should be possible since there is nothing syntactically wrong here.

+0

将'compile'更改为'link',因为这不是编译器问题。 – stijn

回答

12

使用下面的代码,并确保在构建之前运行qmake(Build> Run qmake)。

#include <QApplication> 

class MyApp : public QApplication { 
    Q_OBJECT 
public: 
    MyApp(int argc, char* argv[]); 
}; 

MyApp::MyApp(int argc, char* argv[]) : 
    QApplication(argc,argv) { 
} 

int main(int argc, char* argv[]) { 
    MyApp app(argc,argv); 
    return app.exec(); 
} 

#include "main.moc" 

说明:当包括Q_OBJECT宏,这个信号QT做一堆的东西,不是标准C++,如信号和槽。它通过运行moc来做到这一点,这在很大程度上是一个代码生成器。运行qmake创建元数据,以便在您的项目建立时知道哪些文件为moc等。

+1

这工作正常。但是当我将声明部分放入单独的头文件中时,我仍然不知道为什么它没有包含.moc文件。 – Karsten

+2

你很少需要明确包含任何'.moc'文件。 Qt为你处理这个问题。实际上,我曾经使用过的* only *时间就是在创建像上面那样只有'main.cpp'的示例程序时。我认为原因是'qmake'自动为你处理扫描头文件,而不是cpp文件,因为它们通常不包含需要'moc'-ed的东西。 http://doc.qt.nokia.com/latest/moc.html –

3

我认为你需要MOC文件,包括在底部产生的main.moc。

0

我刚刚遇到了同样的问题,它已被更改字符集我从Unicode到ANSI头的解决。

相关问题