Personal Cmake cheating sheet

Global settings

Assuming the structure of the project xxx is like below

1
2
3
4
5
6
7
8
9
10
11
12
13
xxx/-
|
src/
|
A.h
A.cpp
external/-
|
tinyexpr/
json/
cmake/-


1
2
3
4
5
6
cmake_minimum_required(VERSION 3.x)
# set min cmake version
project(xxxx)
# set ${PROJECT_NAME} as xxx
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmakes)
# add ${CMAKE_CURRENT_SOURCE_DIR}/cmakes to cmake search path

define new function

take the exmple of copy header function for project xxxx, it will copy xxxx header files into the build directory and generate an /include directory in binray directory (suitable when you want to export a library). It can be written in a file called “/cmakes/xxx_copy_headers.cmake”. To use it, add the line

1
include(xxx_copy_headers)

in the main cmakelist.txt.
1
2
3
4
5
6
7
8
9
# 
function(xxx_copy_headers)
foreach(filepath IN ITEMS ${ARGN})
get_filename_component(filename "${filepath}" NAME)
if(${filename} MATCHES ".*\.(hpp|h|ipp)$")
configure_file(${filepath} ${PROJECT_BINARY_DIR}/include/xxx/${filename})
endif()
endforeach()
endfunction()

add external header only lib (proper cmake itself)

take example of the lib json

1
2
3
add_library(json INTERFACE)
target_include_directories(json SYSTEM INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/external/json/include)
# in this case all headers are in xxx/external/json/include

add external libs that are not cmake projects

1
2
3
add_library(tinyexpr ${CMAKE_CURRENT_SOURCE_DIR}/external/tinyexpr/tinyexpr.c)
# add library together with the necessary source files
target_include_directories(tinyexpr SYSTEM PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/external/tinyexpr)
1
2
3
4
5
6
7
set(SOURCES
src/A.h
src/A.cpp)
add_library(xxx_lib ${SOURCES})
target_link_libraries(xxx_lib PUBLIC
json
tinyexpr)