2012-03-09 310 views
2

我正在使用Qt,CMake和VS2010編譯器。當我鏈接一小段測試代碼時,似乎存在一個問題。該接頭提供了以下錯誤:Qt程序沒有鏈接,沒有生成moc文件

plotter.cpp.obj : error LNK2001: unresolved external symbol "public: virtual str 
uct QMetaObject const * __thiscall Plotter::metaObject(void)const " (?metaObject 
@[email protected]@[email protected]@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,這怎麼可能?

謝謝!

+1

您是否曾嘗試在plotter.h文件上手動運行moc - 只是爲了檢查是否存在未被解析的東西,或者它是cmake的錯誤 – 2012-03-09 17:39:49

+1

Qt有一個很棒的IDE,您有沒有考慮過使用那個+ qmake? – 2012-03-09 17:47:11

+0

你的文件是如何組織的?你是否將所有的代碼寫入頭文件?如果是這樣,您必須在其底部包含moc_文件。 – 2012-03-09 17:52:03

回答

1

首先,確保您正確使用QT4_AUTOMOC。正如documentation指出的那樣,您仍然需要在源代碼中正確包含移動文件。

另請注意,QT4_AUTOMOC仍被CMake標記爲實驗,因此請確保它實際上符合您的期望並正確生成所需文件。如果不是,請考慮使用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文件似乎很好。

+0

感謝提示,QT4_WRAP_CPP似乎處理兩個頭文件,但生成一個dialog_moc.cxx文件。無論如何,我現在開始使用Qt Creator,它工作正常。 – user1254962 2012-03-10 15:16:54

+0

感謝您指出SOURCE_GROUP。 – 2013-04-09 09:37:44