Generating Build Environment with CMake

suggest change

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.

The file is named CMakeLists.txt and is placed in the project root, and possibly in subdirectories as well. A basic 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, the minimum CMake version it requires, and to generate an executable called “HelloWorld” from main.cpp. cmake --build, used below, was added in CMake 2.8 and is not part of the 2.4 interface named in the file.

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 the source directory free of build artifacts by using an out-of-source build:

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, run this from the build directory so that .. is the source directory:

cmake -G "NMake Makefiles" ..
nmake

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents