GNU开发工具——CMake构建Qt工程实践

GNU开发工具——CMake构建Qt工程实践

一、CMake构建Qt工程

1、Qt工程源码

创建Migration目录,在目录下创建main.cpp文件:

#include 
#include 

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QLabel label(QString("Hello Qt%1!").arg(int(QT_VERSION >> 16)));
    label.setAlignment(Qt::AlignCenter);
    label.resize(200, 100);
    label.show();
    return app.exec();
}

2、Qt4和Qt5兼容宏

编写兼容Qt4和Qt5的CMake宏,QtMigration.cmake文件如下:

# 定义宏QT_USE_MODULES
macro(QT_USE_MODULES _target)
    # Enable AUTOMOC
    set_target_properties(${_target} PROPERTIES AUTOMOC TRUE)
    # Local variables
    set(_modules_qt4)
    set(_modules_qt5)
    # Prepare modules
    foreach(_module ${ARGN})
        list(APPEND _modules_qt4 Qt${_module})
        list(APPEND _modules_qt5 ${_module})
        if(_module MATCHES "Gui")
            list(APPEND _modules_qt5 "Widgets")
        endif(_module MATCHES "Gui")
    endforeach(_module ${ARGN})
    list(REMOVE_DUPLICATES _modules_qt4)
    list(REMOVE_DUPLICATES _modules_qt5)
    # Find Qt libraries
    find_package(Qt5 QUIET COMPONENTS ${_modules_qt5})
    if(Qt5_FOUND)
        qt5_use_modules(${_target} ${_modules_qt5})
    else(Qt5_FOUND)
        find_package(Qt4 QUIET COMPONENTS ${_modules_qt4})
        if(Qt4_FOUND OR QT4_FOUND)
            include(${QT_USE_FILE})
            include_directories(${QT_INCLUDES})
            add_definitions(${QT_DEFINITIONS})
            target_link_libraries(${_target} ${QT_LIBRARIES})
        endif(Qt4_FOUND OR QT4_FOUND)
    endif(Qt5_FOUND)
endmacro(QT_USE_MODULES)

3、CMakeLists.txt编写

编写工程CMakeLists.txt文件,内容如下:

cmake_minimum_required(VERSION 2.8.9)
project(Migration)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})
include(QtMigration.cmake)
QT_USE_MODULES(${PROJECT_NAME} Core Gui)

4、构建工程

Migration工程内创建build目录,进入build目录,进行构建。

cmake ..
make

5、CMake的Qt相关变量

对于Qt4,使用FIND_PACKAGE后,会生成有效的Qt4_FOUND,QT_USE_FILE,QT_INCLUDES,QT_LIBRARIES变量。

FIND_PACKAGE(Qt4 REQUIRED Core Gui)
if(Qt4_FOUND)
    INCLUDE(${QT_USE_FILE})
    INCLUDE_DIRECTORIES(${QT_INCLUDES})
    TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${QT_LIBRARIES})
endif()

对于Qt5,使用FIND_PACKAGE后,会生成有效的Qt5_FOUND,Qt5Core_INCLUDE_DIRS,Qt5Xml_INCLUDE_DIRS,Qt5Gui_INCLUDE_DIRS,Qt5Widgets_INCLUDE_DIRS,Qt5OpenGL_INCLUDE_DIRS,Qt5Widgets_LIBRARIES,Qt5Core_LIBRARIES,Qt5Gui_LIBRARIES,Qt5Xml_LIBRARIES,Qt5OpenGL_LIBRARIES等相应模块的变量。

FIND_PACKAGE(Qt5 REQUIRED Core Gui Widgets OpenGL Xml)
if(Qt5_FOUND)
    INCLUDE_DIRECTORIES(${Qt5Core_INCLUDE_DIRS} ${Qt5Xml_INCLUDE_DIRS}
        ${Qt5Gui_INCLUDE_DIRS} ${Qt5Widgets_INCLUDE_DIRS} ${Qt5OpenGL_INCLUDE_DIRS})
    #定义QT_LIBRARIES
    SET(QT_LIBRARIES ${Qt5Widg

你可能感兴趣的:(c/c++,运维,开发工具)