ps: 最近在写 ros2 ,借机好好梳理下 cmake
一、CMake 示例
1. 单级目录
- 先查询 cmake 版本: cmake --version
- 编写 CMakeLists.txt
# cmake 需要的最低版本
cmake_minimum_required(VERSION 3.22)
# 打印编译信息
message(STATUS "this is a cmake template")
# 项目名称
project(template)
# 添加编译文件
add_executable(template template.cpp)
# 如果目录下文件较多,可以使用 aux_source_directory(<dir> <variable>)
cmake_minimum_required(VERSION 3.22)
message(STATUS "this is a cmake template")
project(template)
# 查找当前目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
add_executable(template $(DIR_SRCS))
- 执行 cmake
# 执行 cmake
cmake .
# cmake 执行后会生成 makefile
# make 进行编译
make
# 接下来运行 生成可执行文件
./template
2. 多级目录
接下来编写简化的 cmake, 源文件 main.cpp 和 math.cpp 只有一句打印语句。
- 顶层 CMakeLists.txt 编写
cmake_minimum_required (VERSION 3.22)
project(template)
message(status "cmakelists.txt --- 顶层")
# 添加 子文件
add_subdirectory(src)
- 源码 CMakeLists.txt 编写
# PROJECT_SOURCE_DIR:指向顶层 CMakeLists.txt 目录
# CMAKE_SOURCE_DIR:CMakeLists.txt 文件的路径所在的目录。
# CMAKE_CURRENT_SOURCE_DIR:正在处理的 CMakeLists.txt 文件所在的目录。
# CMAKE_BINARY_DIR:CMake 构建目录的路径,即在执行 cmake 命令时指定的构建目录。
# CMAKE_CURRENT_BINARY_DIR:当前正在处理的 CMakeLists.txt 文件的构建目录。
# CMAKE_INCLUDE_CURRENT_DIR:包含当前目录的头文件。
include_directories(${PROJECT_SOURCE_DIR}/include/math/)
# 添加子文件
add_subdirectory(math)
message(status "CMakeLists.txt --- main ")
add_executable(template main.cpp)
# 链接库
target_link_libraries(template MathFunction)
- 源码子目录 CMakeLists.txt 编写
# 获取目录下 所有源文件
aux_source_directory(. DIR_SRCS)
message(status "CMakeLists.txt --- math ")
# 引用头文件
include_directories(${PROJECT_SOURCE_DIR}/include/math)
# 编译库
add_library(MathFunction ${DIR_SRCS})
- 执行结果
// main.cpp
#include <iostream>
#include "math.hpp"
int main (int argc, char ** argv)
{
std::cout << "this is main function" << std::endl;
// math 函数内容: 打印一条语句
math();
return 0;
}
3. 常用变量
1. 系统信息
CMAKE_MAJOR_VERSION
CMAKE_MINOR_VERSION
CMAKE_PATCH_VERSION
CMAKE_SYSTEM
CMAKE_SYSTEM_NAME
CMAKE_SYSTEM_VERSION
CMAKE_SYSTEM_PROCESSOR
UNIX
WIN32
# 示例
if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm")
message(STATUS "Configuring for ARM platform")
add_definitions(-DARM_PARAM)
set(ADDITIONAL_LIBRARIES "/path/to/arm/specific/library.so")
elseif(UNIX AND NOT APPLE)
message(STATUS "Configuring for Linux platform")
add_definitions(-DLINUX_PARAM)
else()
message(FATAL_ERROR "Unsupported platform")
endif()
2. 环境变量
CMAKE_BINARY_DIR 通常是项目的顶级构建目录
PROJECT_BINARY_DIR
<projectname>_BINARY_DIR
CMAKE_SOURCE_DIR, PROJECT_SOURCE_DIR, <projectname>_SOURCE_DIR
CMAKE_CURRENT_SOURCE_DIR
CMAKE_CURRRENT_BINARY_DIR
EXECUTABLE_OUTPUT_PATH , LIBRARY_OUTPUT_PATH
PROJECT_NAME