cmake Tutorial => Getting started with cmake (2024)

Remarks

CMake is a tool for defining and managing code builds, primarily for C++.

CMake is a cross-platform tool; the idea is to have a single definition of how the project is built - which translates into specific build definitions for any supported platform.

It accomplishes this by pairing with different platform-specific buildsystems; CMake is an intermediate step, that generates build input for different specific platforms. On Linux, CMake generates Makefiles; on Windows, it can generate Visual Studio projects, and so on.

Build behavior is defined in CMakeLists.txt files - one in every directory of the source code. Each directory's CMakeLists file defines what the buildsystem should do in that specific directory. It also defines which subdirectories CMake should handle as well.

Typical actions include:

  • Build a library or an executable out of some of the source files in this directory.
  • Add a filepath to the include-path used during build.
  • Define variables that the buildsystem will use in this directory, and in its subdirectories.
  • Generate a file, based on the specific build configuration.
  • Locate a library which is somewhere in the source tree.

The final CMakeLists files can be very clear and straightforward, because each is so limited in scope. Each only handles as much of the build as is present in the current directory.

For official resources on CMake, see CMake's Documentation and Tutorial.

Versions

VersionRelease Date
3.92017-07-18
3.82017-04-10
3.72016-11-11
3.62016-07-07
3.52016-03-08
3.42015-11-12
3.32015-07-23
3.22015-03-10
3.12014-12-17
3.02014-06-10
2.8.12.12013-11-08
2.8.122013-10-11
2.8.112013-05-16
2.8.10.22012-11-27
2.8.10.12012-11-07
2.8.102012-10-31
2.8.92012-08-09
2.8.82012-04-18
2.8.72011-12-30
2.8.62011-12-30
2.8.52011-07-08
2.8.42011-02-16
2.8.32010-11-03
2.8.22010-06-28
2.8.12010-03-17
2.82009-11-13
2.62008-05-05

"Hello World" as a library

This example shows how to deploy the "Hello World" program as a library and how to link it with other targets.

Say we have the same set of source/header files as in the http://www.riptutorial.com/cmake/example/22391/-hello-world--with-multiple-source-files example. Instead of building from multiple source files, we can first deploy foo.cpp as a library by using add_library() and afterwards linking it with the main program with target_link_libraries() .

We modify CMakeLists.txt to

cmake_minimum_required(VERSION 2.4)project(hello_world)include_directories(${PROJECT_SOURCE_DIR})add_library(applib foo.cpp)add_executable(app main.cpp)target_link_libraries(app applib) 

and following the same steps, we'll get the same result.

"Hello World" with multiple source files

First we can specify the directories of header files by include_directories() , then we need to specify the corresponding source files of the target executable by add_executable() , and be sure there's exactly one main() function in the source files.

Following is a simple example, all the files are assumed placed in the directory PROJECT_SOURCE_DIR .

main.cpp

#include "foo.h"int main(){ foo(); return 0;} 

foo.h

void foo(); 

foo.cpp

#include <iostream>#include "foo.h"void foo(){ std::cout << "Hello World!\n";} 

CMakeLists.txt

cmake_minimum_required(VERSION 2.4)project(hello_world)include_directories(${PROJECT_SOURCE_DIR})add_executable(app main.cpp foo.cpp) # be sure there's exactly one main() function in the source files 

We can follow the same procedure in the above example to build our project. Then executing app will print

>./appHello World! 

CMake Installation

Head over to CMake download page and get a binary for your operating system, e.g. Windows, Linux, or Mac OS X. On Windows double click the binary to install. On Linux run the binary from a terminal.

On Linux, you can also install the packages from the distribution's package manager.On Ubuntu 16.04 you can install the command-line and graphical application with:

sudo apt-get install cmakesudo apt-get install cmake-gui 

On FreeBSD you can install the command-line and the Qt-based graphical application with:

pkg install cmakepkg install cmake-gui 

On Mac OSX, if you use one of the package managers available to install your software, the most notable being MacPorts (MacPorts) and Homebrew (Homebrew), you could also install CMake via one of them. For example, in case of MacPorts, typing the following

sudo port install cmake  

will install CMake, while in case you use the Homebrew package manger you will type

brew install cmake 

Once you have installed CMake you can check easily by doing the following

cmake --version 

You should see something similar to the following

cmake version 3.5.1CMake suite maintained and supported by Kitware (kitware.com/cmake). 

Simple "Hello World" Project

Given a C++ source file main.cpp defining a main() function, an accompanying CMakeLists.txt file (with the following content) will instruct CMake to generate the appropriate build instructions for the current system and default C++ compiler.

main.cpp (C++ Hello World Example)

#include <iostream>int main(){ std::cout << "Hello World!\n"; return 0;} 

CMakeLists.txt

cmake_minimum_required(VERSION 2.4)project(hello_world)add_executable(app main.cpp) 

See it live on Coliru

  1. cmake_minimum_required(VERSION 2.4) sets a minimum CMake version required to evaluate the current script.

  2. project(hello_world) starts a new CMake project.This will trigger a lot of internal CMake logic, especially the detection of the default C and C++ compiler.

  3. With add_executable(app main.cpp) a build target app is created, which will invoke the configured compiler with some default flags for the current setting to compile an executable app from the given source file main.cpp .

Command Line (In-Source-Build, not recommended)

> cmake ....> cmake --build . 

cmake . does the compiler detection, evaluates the CMakeLists.txt in the given . directory and generates the build environment in the current working directory.

The cmake --build . command is an abstraction for the necessary build/make call.

Command Line (Out-of-Source, recommended)

To keep your source code clean from any build artifacts you should do "out-of-source" builds.

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

Or CMake can also abstract your platforms shell's basic commands from above's example:

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

Switching between build types, e.g. debug and release

CMake knows several build types, which usually influence default compiler and linker parameters (such as debugging information being created) or alternative code paths.

By default, CMake is able to handle the following build types:

  • Debug: Usually a classic debug build including debugging information, no optimization etc.
  • Release: Your typical release build with no debugging information and full optimization.
  • RelWithDebInfo:: Same as Release, but with debugging information.
  • MinSizeRel: A special Release build optimized for size.

How configurations are handled depends on the generator that is being used.

Some generators (like Visual Studio) support multiple configurations. CMake will generate all configurations at once and you can select from the IDE or using --config CONFIG (with cmake --build ) which configuration you want to build. For these generators CMake will try its best to generate a build directory structure such that files from different configurations do not step on each other.

Generators that do only support a single configuration (like Unix Makefiles) work differently. Here the currently active configuration is determined by the value of the CMake variable CMAKE_BUILD_TYPE .

For example, to pick a different build type one could issue the following command line commands:

cmake -DCMAKE_BUILD_TYPE=Debug path/to/sourcecmake -DCMAKE_BUILD_TYPE=Release path/to/source 

A CMake script should avoid setting the CMAKE_BUILD_TYPE itself, as it's generally considered the users responsibility to do so.

For single-config generators switching the configuration requires re-running CMake. A subsequent build is likely to overwrite object files produced by the earlier configuration.

cmake Tutorial => Getting started with cmake (1) PDF - Download cmake for free



Previous Next

cmake Tutorial => Getting started with cmake (2024)

FAQs

How to properly set up CMake? ›

CMake Tutorial
  1. A Basic Starting Point (Step 1) ...
  2. Adding a Library (Step 2)
  3. Adding Usage Requirements for Library (Step 3)
  4. Installing and Testing (Step 4) ...
  5. Adding System Introspection (Step 5) ...
  6. Adding a Custom Command and Generated File (Step 6)
  7. Building an Installer (Step 7)
  8. Adding Support for a Dashboard (Step 8)

How to write a CMake code? ›

Steps
  1. Step 1: A Basic Starting Point. ...
  2. Step 2: Adding a Library. ...
  3. Step 3: Adding Usage Requirements for a Library. ...
  4. Step 4: Adding Generator Expressions. ...
  5. Step 5: Installing and Testing. ...
  6. Step 6: Adding Support for a Testing Dashboard. ...
  7. Step 7: Adding System Introspection. ...
  8. Step 8: Adding a Custom Command and Generated File.

What is CMake and how to use it? ›

CMake is a meta build system that uses scripts called CMakeLists to generate build files for a specific environment (for example, makefiles on Unix machines). When you create a new CMake project in CLion, a CMakeLists. txt file is generated automatically under the project root.

What is the use case of CMake? ›

CMake handles the difficult aspects of building software such as cross-platform builds, system introspection, and user customized builds, in a simple manner that allows users to easily tailor builds for complex hardware and software systems.

Is there something better than CMake? ›

Explore other competing options and alternatives. Other important factors to consider when researching alternatives to CMake include projects. The best overall CMake alternative is GNU Make. Other similar apps like CMake are SCons, GNU Automake, Leiningen, and FinalBuilder.

What is the difference between CMake and CMake? ›

CMake and Make work on different principles. With CMake you specify build targets, and assign source files and various parameters. With Make, you create a set of build rules. Each rule has a target file, a set of dependencies (to the right of the colon), and the commands needed to perform the rule's build task.

Is CMake still used? ›

Many developers who are using Visual Studio Code use a custom make file to compile their embedded software. Make is everywhere in our industry, yet, something like 70% of the software industry uses CMake.

Does CMake need a compiler? ›

If you do not find precompiled binaries for your system, then you can build CMake from source. To build CMake, you will need a modern C++ compiler and the source distribution from the CMake Download page or Kitware's GitLab instance. To build CMake, follow the instructions in README. rst at the top of the source tree.

Does CMake need C++? ›

Both C++ CMake tools for Windows and Linux Development with C++ are required for cross-platform CMake development. In the installer, the Desktop development with C plus plus dropdown is selected and C plus plus C Make tools for Windows is selected."

What do you need CMake for? ›

CMake is an open source build system and configuration tool used to manage the build process of software projects. It allows developers to define the build process in a platform-independent and efficient way by creating a set of configuration files (CMakeLists. txt) that describe how the project should be built.

How to install CMake correctly? ›

Download the latest release of CMake at http://www.cmake.org/download/.
  1. Pick Windows (Win32 Installer).
  2. Run the installer.
  3. When asked for, select “Add CMake to the system PATH for all users”.
  4. Run software installation.

Is CMake free to use? ›

CMake is distributed as free and open-source software under a permissive BSD-3-Clause license.

Should CMake be added to system path? ›

Important!: You must add the CMake folders to the "Path" environment variable. The Windows Installer of CMake has an option to modify the system's environment variables and add the CMake folders to the "Path" variable. Please select this option during installation.

How to set up CMake on Linux? ›

How to download, compile, and install CMake on Linux
  1. Download: $ wget http://www.cmake.org/files/v2.8/cmake-2.8.3.tar.gz.
  2. Extration of cmake source code from downloaded file: $ tar xzf cmake-2.8.3.tar.gz $ cd cmake-2.8.3.
  3. Configuration: ...
  4. Compilation: ...
  5. Installation: ...
  6. Verification:

How to compile and install with CMake? ›

The common steps to build, test, and install software from source code based on CMake are as follows:
  1. Extract source files.
  2. Create build directory and change to it.
  3. Run CMake to configure the build tree.
  4. Build the software using selected build tool.
  5. Test the built software.
  6. Install the built files.

References

Top Articles
This Weekend’s Best L.A. Events, August 2024
4 life-saving tips for when you spot a rattlesnake on the trail
Sallisaw Bin Store
Parc Soleil Drowning
Provider Connect Milwaukee
The Ultimate Guide To Jelly Bean Brain Leaks: Causes, Symptoms, And Solutions
Wyze Thermostat vs Nest: Detailed Comparison
Defense Immunity 2K23 Meaning
Dr. Nicole Arcy Dvm Married To Husband
Syoss Oleo Intense - 5-10 Cool Bruin - Permanente Haarverf - Haarkleuring - 1 stuk | bol
Circloo Unblocked
Probasketball Reference
Elisabeth Fuchs, Conductor : Magazine : salzburg.info
Target Stocker Careers
Craigslist Furniture By Owner Dallas
Fisher-Cheney Funeral Home Obituaries
Shae Cornette Bikini
Newsweek Wordle
13.2 The F Distribution and the F Ratio - Statistics | OpenStax
Ice Dodo Unblocked 76
Clay County Tax Collector Auto Middleburg Photos
Asa Morse Farm Photos
How to Be an Extra in a Movie (and What to Expect)
Food Lion.com/Jobs
Tbom Genesis Retail Phone Number
Madison Legistar
Abby's Caribbean Cafe
Greet In Cheshire Crossword Clue
Vip Market Vetsource
Leonards Truck Caps
Duitse Rechtspraak: is de Duitse Wet op het minimumloon wel of niet van toepassing op buitenlandse transportondernemingen? | Stichting Vervoeradres
Shaw Funeral Home Vici Oklahoma
Craigs List Skagit County
Pokemon TCG: Best Japanese Card Sets
Joy Ride 2023 Showtimes Near Amc Ward Parkway
Jetnet Retirees Aa
Orylieys
Rexella Van Impe Net Worth
Galen Rupp Net Worth
Weather Radar Jamestown
Giant Egg Classic Wow
Fandafia
Sport Clip Hours
Weather Underground Pewaukee
Chess Unblocked Games 66
Who To Start for Fantasy Football Friday Night Football: Week 1 (2024)
Craigslist Farm And Garden Atlanta Georgia
Lubbock Avalanche Journal Newspaper Obituaries
Ideological variation in preferred content and source credibility on Reddit during the COVID-19 pandemic
H'aanit's Third Chapter | Gamer Guides: Your ultimate sou...
Unblocked Games Premium 77
Pnp Telegram Group
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5295

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.