TExcelTAD
Home › Modern CMake (with CTest & CPack) › Compile Features, Definitions & Options

Compile Features, Definitions & Options

Three more target_* commands control how sources are compiled. All of them take PRIVATE/PUBLIC/INTERFACE, exactly like the previous lesson.

target_compile_features: the language standard

There are two ways to ask for C++20:

cmake
# 1. Per target, propagates to consumers (recommended for libraries)
target_compile_features(mylib PUBLIC cxx_std_20)

# 2. Global default for every target created afterwards (fine for applications)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)   # fail instead of silently falling back
set(CMAKE_CXX_EXTENSIONS OFF)         # -std=c++20 instead of -std=gnu++20

A compile feature is a minimum: if a library says cxx_std_17 and the app says cxx_std_20, the app is compiled with C++20, which satisfies both. When a library's headers need C++20 (concepts, std::span in signatures), make the feature PUBLIC so consumers can't compile it with an older standard.

bash · try it yourself
mkdir -p std && cd std
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Std LANGUAGES CXX)
set(CMAKE_CXX_EXTENSIONS OFF)
add_library(ranges_lib STATIC lib.cpp)
target_compile_features(ranges_lib PUBLIC cxx_std_20)
add_library(old_lib STATIC old.cpp)
target_compile_features(old_lib PUBLIC cxx_std_14)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE ranges_lib old_lib)
CM
echo 'int lib() { return 1; }' > lib.cpp
echo 'int old() { return 2; }' > old.cpp
echo 'int main() { return 0; }' > main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build -v | awk '/c\+\+ .* -c /{f=$NF; sub(/.*\//,"",f); for(i=1;i<=NF;i++) if($i ~ /^-std/) print f ": " $i}'
lib.cpp: -std=c++20
old.cpp: -std=c++17
main.cpp: -std=c++20

app got -std=c++20, the highest requirement among everything it links. Notice also that old_lib asked for C++14 but got -std=c++17: GCC 13 already defaults to (GNU) C++17, CMake never lowers the standard below the compiler's default, and because extensions are off it has to spell the default out as -std=c++17. You can also ask for individual features (cxx_constexpr, cxx_variadic_templates), but the cxx_std_NN meta-features are what projects use today.

target_compile_definitions: preprocessor macros

cmake
target_compile_definitions(app PRIVATE
  APP_VERSION="${PROJECT_VERSION}"      # -DAPP_VERSION="1.2.0"
  USE_FAST_PATH                         # -DUSE_FAST_PATH
  
lt;
lt;CONFIG:Debug>:APP_DEBUG_CHECKS>) # only in Debug builds

Write definitions without -D; CMake adds it (and /D for MSVC) and handles the quoting. A definition that a public header checks (#ifdef MYLIB_SHARED) must be PUBLIC, or the library and its users will see different versions of the header, which is an ODR violation that may crash at run time.

target_compile_options: everything else

Warnings, sanitizers and code generation flags go here. Flags are compiler-specific, so wrap them in generator expressions that test the compiler:

bash · try it yourself
mkdir -p warn && cd warn
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Warn LANGUAGES CXX)

# Warnings as an INTERFACE target: link it into your own targets only.
add_library(project_warnings INTERFACE)
target_compile_options(project_warnings INTERFACE
  
lt;
lt;CXX_COMPILER_ID:GNU,Clang>:-Wall -Wextra -Wshadow -Wconversion>
lt;
lt;CXX_COMPILER_ID:MSVC>:/W4>) add_executable(app main.cpp) target_link_libraries(app PRIVATE project_warnings) target_compile_definitions(app PRIVATE APP_VERSION="1.2.0") CM cat > main.cpp <<'SRC' #include <cstdio> int scale(double factor) { return factor * 10; } int main() { std::printf("v%s scale=%d\n", APP_VERSION, scale(1.5)); } SRC cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null cmake --build build ./build/app
[1/2] Building CXX object CMakeFiles/app.dir/main.cpp.o
/home/learner/warn/main.cpp: In function ‘int scale(double)’:
/home/learner/warn/main.cpp:2:42: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
    2 | int scale(double factor) { return factor * 10; }
      |                                   ~~~~~~~^~~~
[2/2] Linking CXX executable app
v1.2.0 scale=15

-Wconversion caught the implicit double → int conversion (GCC reports it as -Wfloat-conversion, one of the warnings -Wconversion enables). Putting the warning flags in an INTERFACE target called project_warnings is a common pattern: your own targets link it, third-party code you add with add_subdirectory or FetchContent doesn't, so you don't drown in warnings from other people's code.

Language-specific options

In a mixed C/C++ project, a C++-only flag must not reach the C compiler.

lt;COMPILE_LANGUAGE:…> restricts an option to one language:

cmake
target_compile_options(engine PRIVATE
  
lt;
lt;COMPILE_LANGUAGE:CXX>:-fno-rtti>
lt;
lt;COMPILE_LANGUAGE:C>:-std=c17>)

Link options

target_link_options is the linker counterpart (-Wl,--gc-sections, -fsanitize=address). Sanitizers need the flag at compile and link time, so they are usually added to both:

cmake
option(ENABLE_ASAN "Build with AddressSanitizer" OFF)
if(ENABLE_ASAN)
  target_compile_options(project_warnings INTERFACE -fsanitize=address -fno-omit-frame-pointer)
  target_link_options(project_warnings INTERFACE -fsanitize=address)
endif()

Don't touch CMAKE_CXX_FLAGS

CMAKE_CXX_FLAGS is a string the user controls (-DCMAKE_CXX_FLAGS=…, or the CXXFLAGS environment variable on the first configure). If the project appends to it with set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall"), every target gets the flags, including third-party code, and the flags can't be scoped or propagated. The Anti-Patterns field notes show the failure; target_compile_options is the fix.

Test yourself

A library requires cxx_std_17 PUBLIC, the app requires cxx_std_20. What standard is the app compiled with?

  1. C++17
  2. C++20
  3. Both, causing an error
  4. The compiler's default

Your public header has #ifdef MYLIB_USE_DOUBLE. With which scope do you define it?

  1. PRIVATE
  2. PUBLIC
  3. INTERFACE
  4. As a global add_definitions

Why keep warning flags in an INTERFACE library like project_warnings?

  1. They compile faster
  2. Only your own targets link it, so third-party code isn't compiled with your strict warnings
  3. INTERFACE libraries are required for flags
  4. It makes warnings errors