CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。
cmake-make方式,cmake处理工程文件之间的关系,make过程调用g++来编译程序,我们对项目的编译管理只需维护一个至多个的CMakeLists.txt文件极大地降低了维护工程的难度。
安装配置CMake
首先在官网下载cmake-3.15.3-Linux-x86_64.tar.gz
https://github.com/Kitware/CMake/releases/download/v3.15.3/cmake-3.15.3-Linux-x86_64.tar.gz
卸载旧版本:sudo apt-get autoremove cmake1
解压:tar zxvf cmake-3.12.2-Linux-x86_64.tar.gz
查看:tree -L 2 cmake-3.15.3-Linux-x86_64
1 | cmake-3.15.3-Linux-x86_64 |
移动:sudo mv cmake-3.15.3-Linux-x86_64 /opt/cmake-3.15.3
创建软连接:sudo ln -sf /opt/cmake-3.15.3/bin/* /usr/bin/
查看版本:cmake –version
gui界面:cmake-gui
安装make:sudo apt install make
否则会下面运行程序时遇到以下问题:
1 | CMake Error: CMake was unable to find a build program corresponding to "Unix Makefiles". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool. |
简单使用CMake
使用cmake首先需要一个CMakeLists.txt文件,其包含相关配置信息,最后通过cmake处理该文件生成makefile文件,然后再通过make命令根据该makefile文件的内容编译整个工程。
新建如下文件:
CMakeLists.txt
1 | # 声明要求的 cmake 最低版本 |
project (HELLO) #指定项目名称,生成的VC项目的名称;
>>使用${HELLO_SOURCE_DIR}表示项目根目录
include_directories:指定头文件的搜索路径,相当于指定gcc的-I参数
>> include_directories (${HELLO_SOURCE_DIR}/Hello) #增加Hello为include目录
link_directories:动态链接库或静态链接库的搜索路径,相当于gcc的-L参数
>> link_directories (${HELLO_BINARY_DIR}/Hello) #增加Hello为link目录
add_subdirectory:包含子目录
>> add_subdirectory (Hello)
add_executable:编译可执行程序,指定编译,好像也可以添加.o文件
>> add_executable (helloDemo demo.cxx demo_b.cxx) #将cxx编译成可执行文件——
add_definitions:添加编译参数
>> add_definitions(-DDEBUG)将在gcc命令行添加DEBUG宏定义;
>> add_definitions( “-Wall -ansi –pedantic –g”)
target_link_libraries:添加链接库,相同于指定-l参数
>> target_link_libraries(demo Hello) #将可执行文件与Hello连接成最终文件demo
add_library:
>> add_library(Hello hello.cxx) #将hello.cxx编译成静态库如libHello.a
add_custom_target:
message( status|fatal_error, “message”):
set_target_properties( … ): lots of properties… OUTPUT_NAME, VERSION, ….
link_libraries( lib1 lib2 …): All targets link with the same set of libs
helloSLAM.cpp
1 |
|
libhelloSLAM.cpp
1 | //这是一个库文件 |
libhelloSLAM.h
1 |
|
useHello.cpp
1 |
|
运行实例
命令:mkdir build
用来保存中间文件
命令:cd build
命令:cmake ..
cmake ..对上一层文件夹,即代码所在文件夹进行编译,调用cmake对工程进行分析,并输出一些编译器等信息,且在当前目录(build)下生成一些中间文件,最重要的为MakeFile
1 | -- The C compiler identification is GNU 7.4.0 |
命令:make
对工程进行编译,并最终得到可执行程序helloSLAM
1 | Scanning dependencies of target hello_shared |
命令:./helloSLAM
1 | Hello SLAM! |