CMakeLists.txt

Posted megachen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CMakeLists.txt相关的知识,希望对你有一定的参考价值。

示例(在编写CMakeLists.txt前, 创建好src, include, lib, bin, build目录, 其中cmake ..在build目录中执行)

# 一般都会先声明cmake的版本
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(hello_world)

# Release 和 Debug
IF(NOT CMAKE_BUILD_TYPE)
    SET(CMAKE_BUILD_TYPE Release)

ENDIF()

# SET()用于赋值, 类似于 int a = 100
# SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
# SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

# AUX_SOURCE_DIRECTORY也是用于赋值, 只不过是特定于目录的
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src SRC_DIR)

# 设置头文件路径
INCLUDE_DIRECTORIES(
    ${PROJECT_SOURCE_DIR}/include
)

# 指明编译的文件, 创建可执行文件
ADD_EXECUTABLE(main ${SRC_DIR})

# 在MakeFile文件中生成install伪目标指令
INSTALL(TARGETS main DESTINATION ${PROJECT_SOURCE_DIR}/bin)
INSTALL(FILES ${SRC_DIR} DESTINATION ${PROJECT_SOURCE_DIR}/share)

# 指明编译的文件, 创建库, 
ADD_LIBRARY(libname SHARED lib_source_files)

# 添加库的查找目录
LINK_DIRECTORIES(/usr/local/lib)

# 连接库文件
TARGET_LINK_LIBRARIES(main lib_name)

# find_package命令, 让cmake自己找库
FIND_PACKAGE(OpenCV 3 REQUIRED)

# 使用C++的版本
ADD\_DEFINATION(-std=c++)

# 指明编译器
SET(CMAKE\_C\_COMPILER g++)
cmake等帮助
cmake --help-command-list 查看命令
cmake --help-variable-list 查看内置变量

OpenCV的配置

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(demo)

SET(CMAKE_BUILD_TYPE Release)

SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
SET(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)

# 放cmake自己找, 加载模块成功之后就会新增加一些变量, OpenCV_LIBS, OpenCV_INCLUDE_DIRS, OpenCV_LIBRARY_DIRS
FIND_PACKAGE(OpenCV 3.4.1 REQUIRED)

INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
LINK_DIRECTORIES(${OpenCV_LIBRARY_DIRS})

AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src SRC_DIR)
ADD_EXECUTABLE(main ${SRC_DIR})
# OpenCV比较特殊, 下载了V3的, 里面会有V2和V3多个版本在一个目录下, 通过OpenCV_LIBS明确是哪些库, 接着直接连接, 所以我们也不需要上面的LINK_DIRECTORIES
TARGET_LINK_LIBRARIES(main ${OpenCV_LIBS})

INSTALL(TARGETS main DESTINATION ${PROJECT_SOURCE_DIR}/bin)

以上是关于CMakeLists.txt的主要内容,如果未能解决你的问题,请参考以下文章

直接传递编译选项(绕过 CMakeLists.txt)

cmake - CMakeLists.txt 不在根文件夹中(但包含在源代码中)

CMakelists.txt 用于编译 HDF5?

VIM 函数创建 CMakeLists.txt

从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值

不确定如何将 opencv 库添加到 CMakeLists.txt