cmake learn

default

1
2
CMAKE_CURRENT_SOURCE_DIR
PROJECT_SOURCE_DIR

**CMAKE_CURRENT_SOURCE_DIR **

The path to the source directory currently being processed.

This is the full path to the source directory that is currently being processed by cmake.

PROJECT_SOURCE_DIR

This is the source directory of the last call to the project() command made in the current directory scope or one of its parents. Note, it is not affected by calls to project() made within a child directory scope (i.e. from within a call to add_subdirectory() from the current scope).

  • When run in cmake -P script mode, CMake sets the variables CMAKE_BINARY_DIR, CMAKE_SOURCE_DIR, CMAKE_CURRENT_BINARY_DIR and CMAKE_CURRENT_SOURCE_DIR to the current working directory.

scope

PUBLIC

Populates both properties for building and properties for using a target.

PRIVATE

Populates only properties for building a target.

INTERFACE

Populates only properties for using a target.

  • Remember INTERFACE means things that consumers require but the producer doesn’t.

syntax

basic

1
2
3
add_executable()
cmake_minimum_required()
project()
1
2
3
4
5
6
7
8
9
cmake_minimum_required(VERSION 3.10)
project(Tutorial VERSION 2.1)

# Set the variable
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# tells CMake to create an executable using the specified source code files
add_executable(Tutorial tutorial.cxx)

configure_file

copy the input file with the specified CMake variables replaced

1
2
# Copies an <input> file to an <output> file 
configure_file(<input> <output>)

target_include_directories

specify where the executable target should look for include files

1
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}")

Adding a Library

1
2
3
4
add_library()
add_subdirectory()
target_include_directories()
target_link_libraries()

add_library

Add a library target called <name> to be built from the source files listed in the command invocation

1
add_library(MathFunctions MathFunctions.cxx mysqrt.cxx)

add_subdirectory

make use of the new library call

1
add_subdirectory(MathFunctions)

Adding Usage Requirements for a Library

1
2
3
4
5
6
7
8
9
10
target_compile_definitions()
target_compile_options()
target_include_directories()
target_link_directories()
target_link_options()
target_precompile_headers()
target_sources()
add_library()
target_compile_features()
target_link_libraries()

Adding Generator Expressions

1
2
3
4
cmake-generator-expressions(7)
cmake_minimum_required()
set()
target_compile_options()

Installing and Testing

1
install()

Adding System Introspection

1

Packaging an Installer

1
cpack

Selecting Static or Shared Libraries

1
option(BUILD_SHARED_LIBS "Build using shared libraries" ON)

Adding Export Configuration