Why is this simple Qt application not a link

I tried to write a simple Qt application as follows:

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(); } 

But when I tried to compile and link it with Qt Creator 2.3.1 (Qt 4.7.4), I get 3 errors of unresolved external characters:

  • main.obj: -1: error: LNK2001: unresolved external character
    "public: virtual struct QMetaObject const * __thiscall MyApp :: metaObject (void) const"
    (? Metaobject @MyApp @@ UBEPBUQMetaObject @@ XZ). "

  • main.obj: -1: error: LNK2001: unresolved external character
    "public: virtual void * __thiscall MyApp :: qt_metacast (char const *)"
    (? Qt_metacast @MyApp @@ UAEPAXPBD @Z). "

  • main.obj: -1: error: LNK2001: unresolved external character
    "public: virtual int __thiscall MyApp :: qt_metacall (enumeration QMetaObject :: Call, int, void * *)"
    (? Qt_metacall @MyApp @@ UAEHW4Call @QMetaObject @@ HPAPAX @Z). "

I think they are somehow related to the MetaObjectCompiler Qt, but I cannot find a solution. I know that this is not considered a good programming style in C ++ to put declarations and definitions in a single file, but it is not. In my opinion, this should be possible, since there is nothing syntactically wrong here.

+6
source share
4 answers

Use the code below and remember to run qmake (Build> Run qmake) before creating.

 #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" 

Explanation: When you enable the Q_OBJECT macro, it signals Qt to do a bunch of things that are not standard C ++, such as signals and slots. He does this by running moc , which is pretty much a code generator. Running qmake creates metadata, so when your project is built, it knows which files should be moc , etc.

+12
source

I think you need to compile the file and include the resulting main.moc at the bottom.

+3
source

I think this has something to do with QMake. This does not mean that the executable application cannot see the exported DLL class. This means that the obj file for the class does not exist. Starting QMake from the QT Creator Build menu, and then it seems to work.

Why is this simple Qt application not related

0
source

I just met the same problem and it was solved by changing the character set of my header from Unicode to ANSI.

0
source

Source: https://habr.com/ru/post/902241/


All Articles