我使用的是Qt、CMake和VS2010编译器。当我链接一小段测试代码时,似乎出现了问题。链接器给出以下错误:
plotter.cpp.obj : error LNK2001: unresolved external symbol "public: virtual str
uct QMetaObject const * __thiscall Plotter::metaObject(void)const " (?metaObject
@Plotter@@UBEPBUQMetaObject@@XZ)...
(持续了一段时间)
当我试图从以下代码中的QObject继承时,会发生错误:
class Plotter : public QObject
{
Q_OBJECT
public:
如果我省略了Q_OBJECT,程序会链接,但在运行时我不能使用类槽。我注意到没有为plotter.h生成moc文件。这是我的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})
为dialog.cpp生成了一个moc文件,但没有为plotter.cpp生成,这怎么可能?
谢谢!
首先,确保正确使用QT4_AUTOMOC。正如文档所指出的,您仍然需要在源代码中正确地包含mocced文件。
还要注意,CMake仍然将QT4_AUTOMOC标记为实验性的,因此请确保它确实做到了您所期望的,并正确地生成了所需的文件。如果没有,请考虑使用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})
除此之外,您的CMake文件似乎还不错。