MOC error message when building a small single file Qt program


Just a reminder for myself, because I will certainly stumble over it again in the future:

One of my projects was using Qt and was split into several files and subfolders, with several CMakeLists.txt files to it. In it, I made all the required CMake-Qt-Magic, so that CMake and Qt with MOC was working (too much for here, look it up in the source code)… — and everything built fine.

Then I took this as a foundation for a minimalistic Qt test program: Just one source code file (main.cpp), no header file, and one CMakeLists.txt, all in a single directory. Additionally, I slimmed down the CMakeLists.txt and adjusted the values in it… The CMake generator was happy, but Visual Studio failed to build the solution with an error message like this:

The file includes the moc file “moc_main.cpp”, but could not find header “main{.h,.hh,.h++,.hm,.hpp,.hxx,.in,.txx}”

After some investigation, I discovered my mistake. Taken from some StackOverflow posts, which had it from the official documentation (of Qt or CMake):

  • If Q_OBJECT is in the foo.h (i.e. QObject is declared in the header file), then don’t forget to add #include "moc_foo.cpp" in the corresponding foo.cpp, preferably at the end of the file.

  • If Q_OBJECT is in the foo.cpp (i.e. QObject is declared in the source file), then don’t forget to add #include "foo.moc" (in foo.cpp itself), preferably at the end of the file.

So, after changing #include "moc_main.cpp" to #include "main.moc" in my main.cpp, all went smooth.

Update: Hm, I’m not paying much attention to my own writings, it seems: I’ve already mentioned this (Q_OBJECT and moc_*/*.moc files) in a previous entry*sigh*

Leave a comment

Your email address will not be published.