CMake for Cross-Platform C++

Modern target-based CMake: usage requirements that propagate correctly, install and export so downstream projects get real imported targets, presets, generators, and the directory-scoped anti-patterns that still dominate legacy CMakeLists files.

Overview

Old CMake vs modern CMake

CMake has been the default answer for cross-platform C++ for a decade, but most codebases contain CMake written before 2014. That style sets global, directory-scoped state (include_directories, link_directories, add_definitions, CMAKE_CXX_FLAGS) that applies to every later target in the directory and its children. It works until targets need different things; then every target gets every flag and nobody knows which are load-bearing.

Picture the two styles side by side. In the pre-2014 style, one set of directory-wide flags flows down to target A and target B alike, whether either needs them or not. In modern CMake, a library such as core carries its own PRIVATE and INTERFACE requirements, and an app that names it in target_link_libraries receives core's consumer requirements and nothing else.

Key concepts

  • Target
  • Usage requirement
  • PUBLIC / PRIVATE / INTERFACE
  • Generator expression
  • BUILD_INTERFACE and INSTALL_INTERFACE
  • find_package CONFIG mode
  • install(EXPORT) and export()
  • CMakePresets.json

Interview questions

  • Explain PUBLIC, PRIVATE, and INTERFACE in target_link_libraries and what goes wrong when you get them wrong.
  • Walk through making a library consumable by downstream projects via find_package with imported targets.
  • What are generator expressions, and why is BUILD_INTERFACE versus INSTALL_INTERFACE necessary?
  • Compare the CMake generators, and explain what breaks when you assume CMAKE_BUILD_TYPE.
  • How do you choose between FetchContent, find_package, and a package manager for dependencies?
  • Name the modern CMake anti-patterns and explain what each one actually breaks.

Sign up free to read the full topic

More DevOps topics

Start free on Cariara · Coding problems · System design studio