2011-11-23 57 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頭的解決。

相關問題