When is time to include "moc_XXX.cpp" at bottom of a cpp file



  • When developing Qt in depth, We always encounter problems on moc and virtual table. C++ provide us such complicated infrastructures: multi-inheritance, polymorphic, virtual inheritance, etc. And Qt provide us a bunch of more key words: signal/slots, moc, which confuses us a lot.

    In my practice, some bug may be hidden, the program crashes with meaningless debug informations. I followed the article on "Debugging Techniques", the last topic, I added "moc_XXXX.cpp" at bottom of each cpp file, the problem disappears. But who can give use a summary in which scenarios do we need to include the line there? Thanks in advance.



  • short answer: if you have Q_OBJECT in a .cpp file then you have to #include the moc_ file



  • @VRonin Oh, maybe in my practice, some class does follow Qt's role that Q_OBJECT only exist in header file.



  • But I have some experience that when missing "moc_XXX.cpp", even though no Q_OBJECT is present in header file, the compiler is missing essential information that could produce incorrect program at the time. adding this line could prevent the confusing problems from happending, this is especially for Qt plugins.


  • Qt Champions 2017

    Hi
    the #include "moc_XXXX.cpp" at bottom of cpp file is to get around the fact
    that moc tools only runs on .h files.
    So often seen in main.cpp examples where no main.h was created.

    I have made a few Designer plugins for Creator and never had a issue where i had to include the
    moc_ (in .cpp) to get it to link.

    Do you have a sample where even with a .h file but not Q_OBJECT in class, you had
    to include it ?


  • Moderators

    In my projects, I follow these rules:

    1. If I create a new class that inherits QObject (directly or indirectly), I always put the definition in a .h file and not a .cpp file.
    2. If I create a new class that inherits QObject (directly or indirectly), I always give it the Q_OBJECT macro even if it doesn't use any special moc-related features.

    As a result, I never need to include moc_XXX.cpp

    Also, when I make major changes to my code, I also delete my build folder to remove stale compiler outputs.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.