CMake is an open-source, cross-platform family of tools designed to build, test and package software. CMake is used to control the software compilation process using simple platform and compiler independent configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of your choice. The suite of CMake tools were created by Kitware in response to the need for a powerful, cross-platform build environment for open-source projects such as ITK and VTK.html
1. 简单文件结构和实现流程ios
咱们使用的工程文件结构以下,工程文件夹名为 cmaketest c++
~/cmaketest $ tree . ├── build ├── CMakeLists.txt ├── data ├── libs ├── result └── src └── main.cc
其中 main.cc 文件和 CMakeLists.txt 文件以下展现。 CMakeLists.txt 文件用于告诉 cmake 咱们要对这个目录下的文件进行什么操做, CMakeLists.txt 文件的内容须要遵照 cmake 的语法。这里展现的一个最基本的用法,经过注释很容易理解。并发
1 // cmaketest/src/main.cc 2 #include <iostream> 3 4 using namespace std; 5 6 int main(int argc, char** argv) { 7 8 cout << "Hello world!" << endl; 9 return 0; 10 }
1 # cmaketest/CMakeLists.txt for the project 2 3 # 声明要求的 cmake 最低版本要求 4 cmake_minimum_required( VERSION 2.8 ) 5 6 # 声明一个 cmake 工程 7 project( cmaketest ) 8 9 # 添加一个可执行程序 10 # 基本语法:add_executable( 程序名 源代码文件 ) 11 add_executable( cmaketest ./src/main.cc )
而后进入进行编译,注意因为咱们的 CMakeLists.txt 文件在工程文件的一级目录下,而此时咱们在二级目录 build 文件夹下,须要将路径设为 CMakeLists.txt 所在的路径,所以使用的 cmake .. 的命令。ide
cmake 会输出一些编译信息,而后在当前目录生成一些中间文件,其中最重要的是 Makefile。因为 Makefile 是自动生成的,咱们没必要修改它,直接 make 对工程进行编译便可。编译过程会输出一个编译进度,若是顺利经过,咱们就可获得在 CMakeLists.txt 中声明的可执行文件 cmaketest ,在命令行输入可执行文件的文件名使其运行。函数
$ cd build $ cmake .. -- The C compiler identification is GNU 5.4.0 -- The CXX compiler identification is GNU 5.4.0 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done -- Generating done -- Build files have been written to: /home/cv/cmaketest/build
$ make Scanning dependencies of target cmaketest [ 50%] Building CXX object CMakeFiles/cmaketest.dir/src/main.cc.o [100%] Linking CXX executable cmaketest [100%] Built target cmaketest
$ ./cmaketest
Hello world!
这里咱们使用的cmake-make方式对工程进行编译,cmake过程处理了工程文件之间的关系,而make过程实际上调用了g++来编译程序,使得咱们对项目的编译管理工做,从输入一串g++命令,变成了维护若干个比较直观的CMakeLists.txt文件,这明显下降了维护整个工程的难度。ui
并且当咱们想要发布源代码时,通常都不但愿把文件编译和运行的中间文件一并发布,所以咱们这里建了一个名为build的目录,将编译和运行过程当中产生的中间文件和缓冲文件与源代码很好地隔离开来,发布源码时,直接将改文件夹删掉便可,方便快捷。spa
2. 调用工程目录下子文件夹下的头文件命令行
在libs文件夹下新建func.h和func.cc两个库文件,并在main.cc中调用其中定义的函数,三个文件的源代码内容以下。code
~/cmaketest $ tree . ├── build ├── CMakeLists.txt ├── data ├── libs │ ├── func.cc │ └── func.h ├── result └── src └── main.cc
其中main.cc以及func.h和func.cc文件内容以下所示。
Reference