Understanding Generator Expressions
Let's learn about generator expression evaluating a full path to the target's binary file.
We'll cover the following
CMake builds the solution in three stages: configuration, generation, and running the build tool. Generally, we have all the required data during the configuration stage. But every once in a while, we encounter the chicken and the egg problem. For example, a target needs to know the path of a binary artifact of another target, but that information is only available after all the list files are parsed and the configuration stage is complete.
How do we deal with that kind of problem? We could create a placeholder for that information and postpone its evaluation to the next stage: the generation stage.
Generator expressions
This is what generator expressions (sometimes called genexes) do. They are built around target properties such as LINK_LIBRARIES
, INCLUDE_DIRECTORIES
, COMPILE_ DEFINITIONS
, propagated properties, and many others, but not all. They follow rules similar to conditional statements and variable evaluation.
It's worth noting that expressions are generally evaluated in the context of the target using the expression (unless explicitly stated otherwise).
Note: Generator expressions will be evaluated at the generation stage (when the configuration is complete and the buildsystem is created), which means that we can't capture their output into a variable and print it to the console very easily. To debug them, we can use either of these methods:
Write it to a file (this specific version of the
file()
command supports generator expressions):file(GENERATE OUTPUT filename CONTENT "$<...>")
Add a custom target and build it explicitly from the command line:
add_custom_target(gendbg COMMAND ${CMAKE_COMMAND} -E echo "$<...>")
General syntax
Let's take the simplest possible example:
Get hands-on with 1400+ tech skills courses.