[c++] Getting Started - CMake

 

CMake is an open-source cross platform build system, according to CMake's creator, Kitware.

But CMake is not actually  a build system. What CMake provides is an easy way to build C/C++ projects accross platform. CMake generates a cofiguration for your existing compiler system, e.g. make. CMake focus on cross platform configuration, dependecies, testing, packing, installation.

 

CMake also includes tools for finding libraries, e.g. boost. That make it simpler to build project that have external dependencites and by using the tools rather than hard coding paths.

Included with CMake is CTest, a test deriver program. That make it easy to run a project's test program and/or scripts.

Once you have configured your project to be installed, you can also package your project using the included CPack utility. A varity of packages can be created including tar files, zip files or an installer.

 

Example 1

CMakeLists.txt

# cmake_minimum_requried(VERSION version [FATAL_ERROR])
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

# project(name)
project("To Do List")

# add_executable(target sources...)
add_executable(toDo main.cc ToDo.cc)

you may notice that header files are not listed. CMake handles dependencies automatically, so headers dont' need to be listed

main.cc

cmake_minimum_required should be used in all top level CMakeLists.txt. If you are not sure which version to use, then use the version of CMake you have installed

#include "ToDo.h"

int main(int argc, char** argv){
    ToDo list;
    return 0;
}

ToDo.h

#ifndef TODO_H
#define TODO_H

class ToDo{
public:
    ToDo();
    ~ToDo();
};

#endif // TODO_H

ToDo.cc

#include "ToDo.h"

ToDo::ToDo() { } 
ToDo::~ToDo() { }

 

CMake's documentation suggest that out-of-source build be done rather than in-source build, so that we can clear build by simply delete the build folder.

> cd <project root directory>
> mkdir build
> cd build
> cmake -G "Unix Makefiles" ..    # cmake -G <generator name> <path to soruce>
> ls
CMakeCache.txt      CMakeFiles          Makefile            cmake_install.cmake 
> make

The path of <path to source> contains your top level CMakeLists.txt. 

cmake command generates serveral files, which should not be edited by hands.

  • Makefile is the most important one to us as we use it to build our projeect
  • CMakeCache.txt is important to CMake as it stores a varity of information and settings for the project.

Run make to build our target executable, based on the generated Makefile. Makefile suppress standard output. We may output detail by using:

> make VERBOSE=1

 

If you modified the files you had used before, you simply need to run make again. The Makefile generated by CMake will automatically run cmake again if you modified your CMakeListx.txt.

 

Reference:

CMake Tutorial, JohnLamp.net

CMake Tutorial – Chapter 1: Getting Started, JohnLamp.net

 

posted @ 2017-03-26 17:39  TonyYPZhang  阅读(238)  评论(0编辑  收藏  举报