How it works

The interesting part in the hello-world.cpp example is the conditional compilation based on the preprocessor definitions IS_WINDOWS, IS_LINUX, or IS_MACOS:

std::string say_hello() {#ifdef IS_WINDOWS  return std::string("Hello from Windows!");#elif IS_LINUX  return std::string("Hello from Linux!");#elif IS_MACOS
  return std::string("Hello from macOS!");#else  return std::string("Hello from an unknown system!");#endif}

These definitions are defined at configure time by CMake in CMakeLists.txt by using target_compile_definitions before being passed on to the preprocessor. We could have achieved a more compact expression without repeating if-endif statements and we will demonstrate this refactoring in the next recipe. We could also ...

Get CMake Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.