Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CMake Basics

CMake Basics

CMake is a cross-platform build system generator used to manage the compilation of C/C++ projects.

By writing a CMakeLists.txt configuration file you define build rules, dependencies and compile options; CMake then generates platform-specific build files (such as Makefiles on Unix or Visual Studio solutions on Windows).


The CMakeLists.txt file

CMakeLists.txt is CMake's core configuration file; every CMake project needs at least one.

CMake reads the commands in the file to learn the project structure, source file list and compilation requirements.

Basic Syntax

CMakeLists.txt consists of a series of CMake commands, each in the form: command_name(argument_list).

Below are the most commonly used commands when building a CMake project, with examples.

Specify the minimum CMake version:

Example

Syntax: cmake_minimum_required(VERSION )

This command must be placed at the very top of CMakeLists.txt

Example: require CMake 3.10 or newer

cmake_minimum_required

(

VERSION

3.10

)

Define the project name and languages:

Example

Syntax: project( [...])

The language argument is optional; common values: CXX (C++), C (C language)

Calling project() automatically sets variables such as PROJECT_NAME

project

(

MyProject CXX

)

Add an executable:

Example

Syntax: add_executable( ...)

Compile the specified source files into an executable

add_executable

(

MyApp main.

cpp

utils.

cpp

)

Add a library:

Example

Syntax: add_library( [STATIC | SHARED | MODULE] ...)

STATIC: static library (.a / .lib), embedded directly into the executable at compile time

SHARED: shared library (.so / .dll), loaded at runtime

When no type is given, the BUILD_SHARED_LIBS variable decides

add_library

(

MyLib STATIC library.

cpp

)

Link libraries to a target:

Example

Syntax: target_link_libraries( ...)

Link the specified libraries to a target (an executable or another library)

You can link library targets from your own project or external libraries

target_link_libraries

(

MyApp PRIVATE MyLib

)

Set a variable:

Example

Syntax: set( ...)

Define an ordinary variable, later referenced as ${VariableName}

set

(

CMAKE_CXX_STANDARD

17

)

Set several values at once (a list)

set

(

SOURCES main.

cpp

utils.

cpp

helper.

cpp

)

add_executable

(

MyApp $

{

SOURCES

}

)

Specify header paths for a target:

Example

Syntax: target_include_directories(

          [BEFORE | AFTER]

          [SYSTEM]

          [PUBLIC | PRIVATE | INTERFACE]

          ...)

PUBLIC: both the current target and targets depending on it can use the path

PRIVATE: only the current target can use it

INTERFACE: only other targets depending on the current target can use it

target_include_directories

(

MyApp PRIVATE $

{

PROJECT_SOURCE_DIR

}

/

include

)

Set install rules:

Example

Syntax: install(TARGETS ...

        [RUNTIME DESTINATION ]

        [LIBRARY DESTINATION ]

        [ARCHIVE DESTINATION ]

        [INCLUDES DESTINATION ])

Define where each type of file is installed when make install runs

install

(

TARGETS MyApp RUNTIME DESTINATION bin

)

Conditional statements:

Example

Syntax: if() ... elseif() ... else() ... endif()

CMake conditional expressions include comparisons, logical operations and variable tests

if

(

CMAKE_BUILD_TYPE STREQUAL

"Debug"

)

   

Enable debug information in Debug mode

    message

(

STATUS

"Currently building in Debug mode"

)

    set

(

CMAKE_CXX_FLAGS

"${CMAKE_CXX_FLAGS} -g"

)

else

(

)

   

Enable optimizations in Release mode

    message

(

STATUS

"Currently building in Release mode"

)

    set

(

CMAKE_CXX_FLAGS

"${CMAKE_CXX_FLAGS} -O2"

)

endif

(

)

Custom commands:

Example

Syntax: add_custom_command(

         TARGET

         PRE_BUILD | PRE_LINK | POST_BUILD

         COMMAND [args...]

         [COMMENT ]

         [VERBATIM])

PRE_BUILD: runs before compilation

PRE_LINK: runs before linking

POST_BUILD: runs after the build completes

add_custom_command

(

    TARGET MyApp POST_BUILD

    COMMAND $

{

CMAKE_COMMAND

}

E echo

"Build complete!"

    COMMENT

"Print build completion message"

)

Complete example

Below is a complete CMakeLists.txt example combining several of the commands above.

Example

File path: project_root/CMakeLists.txt

1. Specify the minimum CMake version (must come first)

cmake_minimum_required

(

VERSION

3.10

)

2. Define the project name, version and language

project

(

MyProject VERSION 1.0.0 LANGUAGES CXX

)

3. Set the C++ standard to C++17 and require it

set

(

CMAKE_CXX_STANDARD

17

)

set

(

CMAKE_CXX_STANDARD_REQUIRED ON

)

4. Add a static library target

add_library

(

MyLib STATIC

    src

/

lib

/

core.

cpp

     

Core feature implementation

    src

/

lib

/

helper.

cpp

   

Helper function implementation

)

5. Add an executable target

add_executable

(

MyApp

    src

/

main.

cpp

         

Program entry point

    src

/

utils.

cpp

         

Utility functions

)

6. Specify public header paths for the library target

   PUBLIC means targets using MyLib can also access that path

target_include_directories

(

MyLib PUBLIC $

{

PROJECT_SOURCE_DIR

}

/

include

)

7. Specify private header paths for the executable

target_include_directories

(

MyApp PRIVATE $

{

PROJECT_SOURCE_DIR

}

/

src

)

8. Link MyLib into MyApp

target_link_libraries

(

MyApp PRIVATE MyLib

)

9. Set install rules

install

(

TARGETS MyApp RUNTIME DESTINATION bin

)

install

(

TARGETS MyLib ARCHIVE DESTINATION lib

)

Typical commands to build this project are as follows:



# Create build directory in project root (recommended external build)

$ mkdir build && cd build



# Generate build files

$ cmake ..



# Compile project

$ cmake --build .



# Install to system directory (optional)

$ cmake --install .


Variables and the cache

CMake uses variables to store and pass configuration information; variables can be defined and used in CMakeLists.txt.

There are two kinds of variables, ordinary variables and cache variables, with different scopes and lifetimes.

Ordinary variables

Ordinary variables are defined in CMakeLists.txt and are scoped to the current directory and its subdirectories.

Ordinary variables are recomputed on every CMake run and are not persisted.

Example

Define a string variable

set

(

MY_APP_NAME

"runoob-app"

)

Define a list variable (separated by semicolons or spaces)

set

(

SOURCE_FILES main.

cpp

utils.

cpp

helper.

cpp

)

Use a variable: reference it as ${VariableName}

message

(

STATUS

"Project name: ${MY_APP_NAME}"

)

Use a list variable: loop over each source file

foreach

(

FILE

$

{

SOURCE_FILES

}

)

    message

(

STATUS

"Source file: ${FILE}"

)

endforeach

(

)

Cache variables

Cache variables are stored in CMakeCache.txt and keep their values across multiple CMake runs.

Cache variables are typically used to let users customize build settings during configuration, such as toggling features or specifying an install path.

Cache variable values persist. If you change the default value of a cache variable in CMakeLists.txt, you must delete CMakeCache.txt or rerun cmake for the new default to take effect.

Example

Syntax: set( CACHE )

Optional types: STRING, BOOL, PATH, FILEPATH

If the variable already exists in CMakeCache.txt, set will not overwrite it

Define a string cache variable (an install path the user can change)

set

(

MY_INSTALL_PATH

"/usr/local"

CACHE PATH

"Program installation path"

)

Define a boolean cache variable (a feature switch)

set

(

ENABLE_LOGGING ON CACHE BOOL

"Whether to enable logging"

)

Cache variables are used just like other variables

if

(

ENABLE_LOGGING

)

    message

(

STATUS

"Logging is enabled"

)

    add_definitions

(

DENABLE_LOGGING

)

endif

(

)

Users can change cache variables with the command line -D option:



# Modify cached variables in the cmake command using -D

$ cmake .. -DMY_INSTALL_PATH=/opt/runoob -DENABLE_LOGGING=OFF


Header search paths

In CMake there are two ways to tell the compiler where to look for headers: include_directories() and target_include_directories().

Understanding the difference is important for writing clear, maintainable CMake projects.

include_directories vs target_include_directories

Both add header search paths for the compiler, but they differ in scope and granularity of control.

Feature include_directories() target_include_directories()
Scope Global scope, affecting every target in the current directory and subdirectories Applies only to the specified target and does not pollute other targets
Recommendation Not recommended, except when maintaining legacy CMake projects Recommended; follows modern CMake best practices
Target association Not tied to a particular target and may accidentally affect other targets Explicitly bound to the specified target, making dependencies obvious
Maintainability Poor; global path pollution is easy and hard to debug Good; paths are bound to targets and the logic is clear
Visibility control Cannot precisely control propagation Precisely controlled through PUBLIC, PRIVATE and INTERFACE

Meaning of PUBLIC / PRIVATE / INTERFACE

The key advantage of target_include_directories() is that visibility keywords precisely control how header paths propagate.

The keyword Available to the current target Available to other targets depending on this target Typical scenario
PRIVATE Is No Internal headers needed only by the implementation itself
PUBLIC Is Is Public API headers of a library, needed by both itself and consumers
INTERFACE No Is Header-only library

Example

Scenario: MyLib headers live in the include/ directory

MyLib itself needs include/, and MyApp which uses MyLib also needs include/

PUBLIC: both itself and consumers can access the path

target_include_directories

(

MyLib PUBLIC $

{

PROJECT_SOURCE_DIR

}

/

include

)

PRIVATE: only MyApp itself can access it (internal utility headers)

target_include_directories

(

MyApp PRIVATE $

{

PROJECT_SOURCE_DIR

}

/

src

/

internal

)

INTERFACE: MyLib is a header-only library, needs no compilation itself, and only passes the path to consumers

add_library

(

HeaderOnlyLib INTERFACE

)

target_include_directories

(

HeaderOnlyLib INTERFACE $

{

PROJECT_SOURCE_DIR

}

/

header_only

)


Finding libraries and packages

Many projects depend on external libraries (such as Boost or OpenCV); CMake provides find_package() to detect and configure these dependencies automatically.

The find_package command

find_package() searches for libraries installed on the system and sets corresponding variables (such as header paths, library file paths and imported target names).

Example

Basic usage: find the Boost library without a version constraint

REQUIRED means CMake configuration stops if it is not found

find_package

(

Boost REQUIRED

)

Specify a minimum version: require Boost 1.70 or newer

find_package

(

Boost

1.70

REQUIRED

)

Specify a search path: look for OpenCV under a custom path

find_package

(

OpenCV REQUIRED PATHS

/

path

/

to

/

opencv

)

Using a library that was found

After find_package() succeeds, it usually provides the following:

What is provided Example Description
Imported targets Boost::Boost The modern CMake approach: use them directly with target_link_libraries
Header path variables ${Boost_INCLUDE_DIRS} Legacy usage, combined with include_directories
Library file path variables ${Boost_LIBRARY_DIRS} Legacy usage, combined with link_directories

Strongly recommendedImported targetsstyle (such as Boost::Boost) instead of manually assembling header and library paths. Imported targets handle all compile and link options automatically, reducing configuration errors.

Example using a third-party library

Below is a complete example showing how to bring Boost into a CMake project and use it.

Example

File path: project_root/CMakeLists.txt

cmake_minimum_required

(

VERSION

3.10

)

project

(

MyBoostProject CXX

)

Set the C++ standard

set

(

CMAKE_CXX_STANDARD

17

)

Find the Boost library and fail if it is missing

find_package

(

Boost REQUIRED

)

Add an executable

add_executable

(

MyApp main.

cpp

)

Link Boost using the imported target

Boost::Boost automatically sets header paths and library file paths

target_link_libraries

(

MyApp PRIVATE Boost

::

Boost

)


Notes

Prefer the target_xxx family of commands.include_directories() and link_directories() are global commands that easily cause path pollution. In large projects always use target_include_directories() and target_link_libraries() instead; they make dependencies clearer and easier to maintain.

Always specify the C++ standard.Without CMAKE_CXX_STANDARD the compiler uses its default standard (usually C++98 or C++14, depending on the compiler version). It is also advisable to set CMAKE_CXX_STANDARD_REQUIRED to ON so that an unsupported standard fails immediately.

Understand the difference between PUBLIC / PRIVATE / INTERFACE.Misusing these keywords is the most common trap for CMake beginners. Simple rule: needed by yourself and by consumers -> PUBLIC; needed only by yourself -> PRIVATE; needed only by consumers (such as a header-only library) -> INTERFACE.

Cache variable defaults are not updated automatically.After changing the default in set(... CACHE ...) in CMakeLists.txt, an existing CMakeCache.txt is not overwritten. Delete CMakeCache.txt in the build directory, or the whole build directory, and rerun cmake.