cmake基础常用总结

cmake是干啥的?

百度可以搜到很多,说了也是浪费资源

目的

主要记录自己使用过程中的常用疑问及解答;

常用命令

版本号

cmake_minimum_required(VERSION 3.7)

项目信息

project(cmake_demo)

查找当前目录下的所有文件并将名称保存到DIR_SRCS

aux_source_directory (. DIR_SRCS)
aux_source_directory (./src/intern SRC1)
aux_source_directory (./src SRC2)

头文件查找

include_directories (./)
include_directories (./src)
include_directories (./src/intern)

指定生成目标

  1. 生成可执行文件
    add_executable (dxftest ${DIR_SRCS} ${SRC1} ${SRC2})
  2. 生成动态库
    add_library(libdxf SHARED ${DIR_SRCS})
  3. 生成静态库
    add_library(libdxf STATIC ${DIR_SRCS})

链接库

1
2
target_link_libraries(libdxf libx1)
target_link_libraries(libdxf libx2)

使用cmake编译Qt工程

1
2
3
1. cmake编译Qt的最小版本是2.8.3,当然版本越高支持越好;
2. Qt5.7需要c++11支持,所以如果cmake不支持,则需要手动指定;
set(CMAKE_CXX_STANDARD 11)

查找qt5库

  1. find_package(Qt5Core Qt5Widgets);
  2. find_package的结果就是生成了一些targets可以被target_link_libraries使用;
  3. find_package也会也会生成一些变量用于编译,还有一些宏;
  4. 生成的每个module的目标匹配以Qt5::为前缀的Qt module. 如Qt5::Widgets;
  5. 如find_package(Qt5Widgets)将会生成以下变量
1
2
3
4
5
6
7
8
9
10
Qt5Widgets_VERSION String describing the version of the module.
Qt5Widgets_VERSION_STRING Same as Qt5Widgets_VERSION. Deprecated, use Qt5Widgets_VERSION instead.
Qt5Widgets_LIBRARIES List of libraries for use with the target_link_libraries command.
Qt5Widgets_INCLUDE_DIRS List of directories for use with the include_directories command.
Qt5Widgets_DEFINITIONS List of definitions for use with add_definitions.
Qt5Widgets_COMPILE_DEFINITIONS List of definitions for use with the COMPILE_DEFINITIONS target property.
Qt5Widgets_FOUND Boolean describing whether the module was found successfully.
Qt5Widgets_EXECUTABLE_COMPILE_FLAGS String of flags to be used when building executables.

Note: 其他类似,注意变量区分大小写。

链接库

target_link_libraries(example Qt5::Core Qt5::Widgets)

Qt build tools:moc,rcc,uic

moc

set(CMAKE_AUTOMOC ON):控制是否主动去对文件进行元处理

uic

  1. set(CMAKE_AUTOUIC ON)
  2. 如果文件#include “ui_.h”或工程包含.ui,则会触发uic;
  3. 可以通过AUTOUIC_SEARCH_PATHS寻找ui文件的路径;

rcc

  1. set(CMAKE_AUTORCC ON)
  2. add_executable(exe main.cpp resource_file.qrc)

最小例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
cmake_minimum_required(VERSION 2.8.11)
project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# Find the QtWidgets library
find_package(Qt5Widgets)

# Tell CMake to create the helloworld executable
add_executable(helloworld WIN32 main.cpp)

# Use the Widgets module from Qt 5.
target_link_libraries(helloworld Qt5::Widgets)

官方url

[cmake-qt-manual][http://doc.qt.io/qt-5/cmake-manual.html]

FAQ

1.