Examples to Try Out
Let's learn about some of the uses for generator expressions.
Everything is easier to grasp when there's a good practical example to support the theory. Here are some of the uses for generator expressions:
Build configurations
There may be cases where we'd like to act differently based on what kind of build (Debug
, Release
, and so on) we're making.
A simple and easy way to do so is by utilizing the $<CONFIG>
generator expression:
target_compile_options(tgt $<$<CONFIG:DEBUG>:-ginline-points>)
The preceding example checks whether the config equals DEBUG
; if that's the case, the nested expression is evaluated to 1
. The outer shorthand if
expression then becomes true
, and our -ginline-points
debug flag gets added to the options.
System-specific one-liners
Generator expressions can also be used to compact verbose if
commands into neat one-liners. Let's suppose we have the following code:
if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")target_compile_definitions(myProject PRIVATE LINUX=1)endif()
It tells the compiler to add -DLINUX=1
to the arguments if this is the target system. While this isn't terribly long, it could be easily replaced with an elegant ... ...