Avoiding global variables using target_sources

The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-07/recipe-08 and has a C++ example. The recipe is valid with CMake version 3.5 (and higher) and has been tested on GNU/Linux, macOS, and Windows.

In this recipe, we will discuss an alternative approach to the previous recipe and assemble the different CMakeLists.txt files without using add_subdirectory, but using module includes. This approach is inspired by https://crascit.com/2016/01/31/enhanced-source-file-handling-with-target_sources/ and allows us to use target_link_libraries to link to targets defined outside of the current directory.

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.