C++ Generating Build Environment with CMake


Example

CMake generates build environments for nearly any compiler or IDE from a single project definition. The following examples will demonstrate how to add a CMake file to the cross-platform "Hello World" C++ code.

CMake files are always named "CMakeLists.txt" and should already exist in every project's root directory (and possibly in sub-directories too.) A basic CMakeLists.txt file looks like:

cmake_minimum_required(VERSION 2.4)

project(HelloWorld)

add_executable(HelloWorld main.cpp)

See it live on Coliru.

This file tells CMake the project name, what file version to expect, and instructions to generate an executable called "HelloWorld" that requires main.cpp.

Generate a build environment for your installed compiler/IDE from the command line:

> cmake .

Build the application with:

> cmake --build .

This generates the default build environment for the system, depending on the OS and installed tools. Keep source code clean from any build artifacts with use of "out-of-source" builds:

> mkdir build
> cd build
> cmake ..
> cmake --build .

CMake can also abstract the platform shell's basic commands from the previous example:

> cmake -E make_directory build
> cmake -E chdir build cmake .. 
> cmake --build build 

CMake includes generators for a number of common build tools and IDEs. To generate makefiles for Visual Studio's nmake:

> cmake -G "NMake Makefiles" ..
> nmake