2013-02-03 117 views
1

我很抱歉我的愚蠢問題。我試圖從類與Qt對象cmake編譯DLL。庫包含使用其他文件中定義的類的函數。在鏈接過程中,我得到類成員的錯誤「未定義引用」。 CMakeList.txt中的錯誤在哪裏?用cmake編譯qt庫

CMakeList.txt:

cmake_minimum_required(VERSION 2.8) 
project(foo)    
set(SOURCE_LIB foo.cpp window.cpp)   
find_package (Qt4 REQUIRED) 
include (${QT_USE_FILE}) 
ADD_DEFINITIONS(-DFOO_LIBRARY) 
add_library(foo SHARED ${SOURCE_LIB}) 
target_link_libraries(foo ${QT_LIBRARIES}) 

foo.h中:

#ifndef FOO_H 
#define FOO_H 

#include "foo_global.h" 

void FOOSHARED_EXPORT hello_world(); 
#endif // FOO_H 

Foo.cpp中:

#include <QApplication> 
#include <QMessageBox> 
#include "window.h" 

void hello_world() 
{ 
    int argc = 0; 
    char ** argv = (char **) 0; 
    QApplication a(argc, argv); 
    Window *w = new Window(); 
    w->Msg(); 
} 

foo_global.h:

#ifndef FOO_GLOBAL_H 
#define FOO_GLOBAL_H 

#include <QtCore/qglobal.h> 

#if defined(FOO_LIBRARY) 
# define FOOSHARED_EXPORT Q_DECL_EXPORT 
#else 
# define FOOSHARED_EXPORT Q_DECL_IMPORT 
#endif 

#endif // FOO_GLOBAL_H 

window.cpp:

#include <QMessageBox> 
#include "window.h" 

void Window :: Msg() 
{ 
    QMessageBox *msg = new QMessageBox(); 
    msg->setText("hello"); 
    msg->exec(); 
} 

window.h中:

#ifndef WINDOW_H 
#define WINDOW_H 

#include <QtGui> 

class Window 
{ 
    Q_OBJECT 
public: 
    void Msg(); 

}; 

#endif // WINDOW_H 

輸出:

Test\build>c:\MinGW\bin\mingw32-make.exe 
Scanning dependencies of target foo 
[ 50%] Building CXX object CMakeFiles/foo.dir/foo.cpp.obj 
[100%] Building CXX object CMakeFiles/foo.dir/window.cpp.obj 
Linking CXX shared library libfoo.dll 
Creating library file: libfoo.dll.a 
CMakeFiles\foo.dir/objects.a(foo.cpp.obj):foo.cpp:(.text$_ZN6WindowC1Ev[Window:: 
Window()]+0x8): undefined reference to `vtable for Window' 
collect2: ld returned 1 exit status 
mingw32-make[2]: *** [libfoo.dll] Error 1 
mingw32-make[1]: *** [CMakeFiles/foo.dir/all] Error 2 
mingw32-make: *** [all] Error 2 

回答

3

所有標頭包含Q_OBJECT宏必須由元對象編譯器處理的類。 因此,您的cmake文件應該如下所示:

cmake_minimum_required(VERSION 2.8) 
project(foo)    
set(LIB_SOURCE foo.cpp window.cpp)   
set(LIB_HEADER foo.h) 
find_package (Qt4 REQUIRED) 
include (${QT_USE_FILE}) 
ADD_DEFINITIONS(-DFOO_LIBRARY) 

QT4_WRAP_CPP(LIB_HEADER_MOC ${LIB_HEADER}) 

add_library(foo SHARED ${LIB_SOURCE} ${LIB_HEADER_MOC}) 
target_link_libraries(foo ${QT_LIBRARIES})