2

I'm using Qt, CMake, and the VS2010 compiler. There seems to be a problem when I'm linking a small piece of test code. The linkers gives the following error:

plotter.cpp.obj : error LNK2001: unresolved external symbol "public: virtual str
uct QMetaObject const * __thiscall Plotter::metaObject(void)const " (?metaObject
@Plotter@@UBEPBUQMetaObject@@XZ)...

(it goes on for a while)

The error occurs when I'm trying to inherit from QObject in the following code:

class Plotter : public QObject
{
        Q_OBJECT
public:

If I leave out the Q_OBJECT, the program links, but I can't use the class slots at runtime. I noticed that no moc file is generated for plotter.h. This is my CMakeLists.txt:

 cmake_minimum_required (VERSION 2.6)
    project (ms)

    SET(CMAKE_BUILD_TYPE "Release")

    FIND_PACKAGE(Qt4)
    INCLUDE(${QT_USE_FILE})
    ADD_DEFINITIONS(${QT_DEFINITIONS})

    LINK_LIBRARIES(
        ${QT_LIBRARIES}
    )

    set(all_SOURCES plotter.cpp main.cpp dialog.cpp)
    QT4_AUTOMOC(${all_SOURCES})
    add_executable(ms ${all_SOURCES})
    target_link_libraries(ms ${LINK_LIBRARIES})

A moc file is generated for dialog.cpp, but not for plotter.cpp, how is this possible?

Thanks!

user1254962
  • 153
  • 5
  • 15

1 Answers1

1

First of all, ensure you are using QT4_AUTOMOC correctly. As the documentation points out, you still need to properly include the mocced files in your sources.

Also notice that QT4_AUTOMOC is still marked as experimental by CMake, so be sure it actually does what you expect and correctly generates the required files. If not, consider switching to the more robust classic solution using QT4_WRAP_CPP:

# notice that you need to pass the *header* here, not the source file
QT4_WRAP_CPP(MY_MOCED_FILES plotter.hpp)

# optional: hide the moced files in their own source group
# this is only useful if using an ide that supports it
SOURCE_GROUP(moc FILES ${MY_MOCED_FILES})

# then include the moced files into the build
add_executable(ms ${all_SOURCES} ${MY_MOCED_FILES})

Apart from that, your CMake file seems fine.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • thanks for the hint, QT4_WRAP_CPP seems to handle both header files, but generates a dialog_moc.cxx file. Anyway, I started with Qt Creator now which works fine. – user1254962 Mar 10 '12 at 15:16
  • 1
    With Qt5 you have to use set(CMAKE_AUTOMOC ON) before add_executable. Vice-versa will cause the OP's problem. – remikz Apr 28 '21 at 19:20