CMake 笔记

                     

贡献者: addis

预备知识 Makefile 笔记

   参考官方教程

1. 常识

2. 常用命令

3. 链接库

4. 函数

   自定义函数如

# 计算一个数的平方
function(compute_square number result_var)
    math(EXPR result "${number} * ${number}")
    set(${result_var} ${result} PARENT_SCOPE)
endfunction()

# 函数调用
set(my_number 5)
compute_square(${my_number} my_result)
message(STATUS "The square of ${my_number} is ${my_result}")

5. CMake Package

如何写 包名Config.cmake(Config Mode)

   如果要写 Find包名.cmake,其实只需要使用 set() 设置若干路径变量即可。一般只有库的作者没有提供 config mode 的 cmake 时才需要用户写这个文件。用 apt 安装的包如果提供了该 cmake 一般也会被搜到。

   要写 包名Config.cmake,需要给 add_library 定义要导出的 target,以及用 set_target_properties 指定库文件和头文件的路径,这样用户导入的时候就不需要再设置一次了。

# MyLibraryConfig.cmake
# Define the paths to the library and include directories
set(MyLibrary_LIBRARIES "${CMAKE_CURRENT_LIST_DIR}/lib/file.a")
set(MyLibrary_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/include")
# Create an imported target for MyLibrary
add_library(MyLibrary STATIC IMPORTED)
# Set the properties for the imported target
set_target_properties(MyLibrary PROPERTIES
  # set lib files location so that user can import the target
  IMPORTED_LOCATION "${MyLibrary_LIBRARIES}"
  # set header files location so that user can import the target
  INTERFACE_INCLUDE_DIRECTORIES "${MyLibrary_INCLUDE_DIRS}"
)
# Optionally, set the MyLibrary_FOUND variable
# to indicate the library was found
set(MyLibrary_FOUND TRUE)
# Minimum CMake version
cmake_minimum_required(VERSION 3.10)

# Project name
project(MyLibrary)

# Set the version (optional)
set(MYLIBRARY_VERSION_MAJOR 1)
set(MYLIBRARY_VERSION_MINOR 0)

# Define the library target
add_library(MyLibrary SHARED IMPORTED)

# Specify the directories for header files
target_include_directories(MyLibrary
    INTERFACE
    # Replace with actual path
    ${CMAKE_CURRENT_SOURCE_DIR}/include
)

# Link the library files (use separate statements
#     for different OSes if needed)
set_target_properties(MyLibrary PROPERTIES
    # Linux
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/mylibrary.so"
    # Windows
    IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/lib/mylibrary.dll"
)

# Define macros required by the library
target_compile_definitions(MyLibrary
    INTERFACE
    MYLIBRARY_DEFINE_1
    MYLIBRARY_DEFINE_2=VALUE  # Example with a value
)

# Export the library target for use in other projects
export(TARGETS MyLibrary FILE MyLibraryConfig.cmake)

6. 内置变量

7. 判断

   参考这里

if(1 或 ON 或 YES 或 TRUE 或 Y)
  ……
elseif(0 或 OFF 或 NO 或 FALSE 或 N 或 IGNORE 或 NOTFOUND)
  这里永远不会执行
elseif(条件 AND (条件 OR 条件) OR NOT 条件)
  ……
elseif(("bar" IN_LIST 变量) OR (file1 IS_NEWER_THAN file2))
  ……
elseif(变量)
  当变量有定义且不是 false constant
if(ENV{变量})
  这里永远不会执行
elseif (DEFINED <name>|CACHE{<name>}|ENV{<name>})
  若定义了变量
elseif (变量1 STREQUAL 变量2)
  比较字符串
elseif (IS_DIRECTORY 某路径)
  判断某路径是否存在
else()
  ……
endif()

8. CMake 与 Visual Studio

9. ccmake 使用

                     

© 小时科技 保留一切权利