cmake的小记录,最近在Linux上整活,正好学一下

暂时不涉及库文件的生成

文件树


1
2
3
4
5
6
# 项目标准文件树
.
├── CMakeLists.txt
├── include
├── linux.sh
└── src
1
2
3
4
5
6
7
8
# cmake后的文件树,可执行文件在bin中,构建在build中
.
├── CMakeLists.txt
├── bin
├── build
├── include
├── linux.sh
└── src

CMakeLists.txt


CMakeLists

感觉CMakeLists放最顶层方便一点,当然模块化的话就通过add_subdirectory递归地构建,基本满足目前的99%需要

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
cmake_minimum_required(VERSION 3.15)

# set the project name
project(test-cmake)

# bin file output
# you can also set others
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)

# include file path
include_directories(${PROJECT_SOURCE_DIR}/include)

# your source files
# you can also use
# set(SRC_LIST ./src/main.cpp ./src/util.cpp ./src/nums.cpp)
aux_source_directory(src SRC_LIST)

if(UNIX)
MESSAGE("\nThis is Linux.\n")
# you can set some config here.
# add_compile_options(-std=c++17 -Wall)
elseif(WIN32)
MESSAGE("This is Windows.")
endif()

# compile_options
# for your gcc/g++
add_compile_options(-std=c++17 -O2 -lpthread -Wall)

# add the executable
add_executable(test-cmake ${SRC_LIST})

有了 CMakeLists.txt 就可以直接在根目录下执行 bash,完成构建和编译,以下给出脚本文件

Linux Bash

1
2
3
4
mkdir ./build
cd ./build
cmake ..
cmake --build . # 统一的接口,不管底层是啥,直接--build即可,不然指明make或ninja等底层

Windows Bat

1
2
3
4
md build
cd .\build
cmake ..
cmake --build .

链接第三方库文件


  • 头文件 - 开发时
  • 静态库.lib - 编译时
  • 动态库.dll - 运行时,不会!大佬教教!
1
2
3
4
5
6
7
8
9
10
11
# 批量引入库文件和头文件
# REQUIRED:找不到库就报错
# COMPONENTS:从库中找子库(模块)xx,比如COMPONENTS Widget表示找到子模块Widget
find_package(OpenCV REQUIRED)
find_package(Qt5 COMPONENTS Core REQUIRED)

# OpenCV_INCLUDE_DIRS 是预定义变量,代表OpenCV库的头文件路径
include_directories(${OpenCV_INCLUDE_DIRS})

# OpenCV_LIBS 是预定义变量,代表OpenCV库的lib库文件
target_link_libraries(YOUR_TARGET_NAME ${OpenCV_LIBS})

参考