c++qtmoc

When do I have to include moc*.cpp in Qt?


I understand the basic concept of why it is better to manually include moc*.cpp instead of leaving moc to do it itself, but I don't quite understand when I have to include it.

Let's say I have mainwindow.cpp and mainwindow.hpp, that require the moc to run on them. Here, I know I have to include moc_mainwindow.cpp in mainwindow.cpp (and not in mainwindow.hpp).

But what if I have foo.cpp that includes mainwindow.hpp, do I have to include moc_mainwindow.hpp in foo.cpp? It just isn't clear to me how this whole moc thing works, so can someone explain this? (and, yes, I did research this on the internet - I read the Qt Documentation about moc but it didn't make it clear to me).


Solution

  • The moc’ed file contains the implementation of the meta object, the signal-slot sugar and few other things. It means that if you compile it more than once you will have duplicated symbols on linking stage.

    Actually your best option would be to not include the moc’ed file and add it as other normal compilation unit of your project. It simplifies your code, prevents linkage errors, and have a good impact in your compilation time when implementation files are modified.

    Nevertheless, if you decide to include the moc’ed file manually you have to do it only in one place to prevent the aforementioned duplicated implementations.

    Another case where a direct include is useful for expressiveness is when you declare a class with the Q_OBJECT in a .cpp file: including the moc’ed in the same file is coherent with the fact that such class belongs to only that file.