基本
编译为可执行文件
add_executable(文件名, 源文件列表)
编译为库
add_library(文件名, 源文件列表)
附加include目录
include_directoies
链接库
target_link_libraries(文件名 库名列表)
添加子项目
add_subdirectory(目录名)
可以将一些配置信息写入CMakeFiles.txt, cmake时生成一个config.h, 然后由源码引用
- 编写 config.h.in
#define MAJOR_VERSION @MAJOR_VERSION@
#define MINOR_VERSION @MINOR_VERSION@
- 编写CMakeLists.txt
# 设置变量
set(MAJOR_VERSION 1)
set(MINOR_VERSION 0)
# 指定config文件生成, 默认生成到了cmake的输出目录
configure_file(config.h.in config.h)
# 将cmake的输出目录包含进来
include_directories(${PROJECT_BINARY_DIR})
- 源码中引用 config.h
#include <iostream>
#include <config.h>
int main(){
std::cout<<"show me:"<<MAJOR_VERSION<<"."<<MINOR_VERSION<<std::endl;
}
选项 option
用于制造一些选项, 然后在CMake的GUI界面作为开关, CMakeLists.txt中可以用if来判断
- 在CMakeLists.txt中定义option,并设定描述和初始值(ON / OFF)
option(USE_OPENGL, "use opengl graphics function to draw", ON)
- 在CMakeLists.txt中只有if来判断是否开启
if (USE_OPENGL)
......
endif(USE_OPENGL)
- 若要在c++代码中使用USE_OPENGL这个宏,
- 需要在 configure_file 语句前定义 option
- 需要在config.h.in 中用 #cmakedefine 来标记这个宏
#cmakedefine USE_OPENGL
之后, 才能在c++文件中使用它
#ifdef USE_OPENGL
#include <gl/gl.h>
#endif
注:
如果是ON, 配置出的config.h 中 就是
#define USE_OPENGL
如果是OFF, 配置出的config.h中就是
/* #undef USE_OPENGL */
添加子项目
- 子项目的文件夹的根目录下要有 CMakeLists.txt, 该文件中无需再定义 cmake_minimun_requird 和 project
add_library(lib1 lib1.cpp)
- 在主工程的CMakeLists.txt中使用add_subdirectory(子工程的目录名)
add_subdirectory(lib1)
- cmake时 会为子工程也生成makefile,由主工程的makefile自动调动
安装
- 安装头文件, 需要放在CMakeLists.txt的最后
install (
FILES 头文件列表
DESTINATION include
) - 安装目标二进制文件, 需要放在CMakeLists.txt的最后
install (
TARGETS 目标文件列表
DESTINATION bin
) - 执行make后, 执行 make install 就能安装, 如遇权限问题就需要执行 sudo make install
- cmake的变量 CMAKE_INSTALL_PREFIX 标识安装目录, linux默认貌似是在 /usr/local/下
Ubuntu install latest CMake version
download a .sh file from https://cmake.org/download/
sudo sh cmake-3.18.3-Linux-x86_64.sh --prefix=/usr/local --exclude-subdir

1579

被折叠的 条评论
为什么被折叠?



