Yet another post in “Matt tries to learn Effective CMake”. This time, it’s generator expressions!
So, I have a code where we want to link in a library only if an
option() is true. So I have (simplified):
target_link_libraries(this PRIVATE MPI::MPI_Fortran) if (BUILD_WITH_FLAP) target_link_libraries(this PRIVATE FLAP::FLAP) endif ()
and this works. But then I thought “Maybe I can make this more compact (and much less readable?) with Generator Expressions!” So I tried:
target_link_libraries(this PRIVATE MPI::MPI_Fortran $<$<BOOL:BUILD_WITH_FLAP>:FLAP::FLAP>)
Now, obviously, if this worked, I wouldn’t be here. When I try this I get:
CMake Error at ESMA_cmake/ecbuild/cmake/ecbuild_add_library.cmake:268 (add_library): Target "MAPL.cap" links to target "FLAP::FLAP" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing?
which is a fancy enough CMake error that I’m not sure what it means.
So, what is the right way to do this? Or should I just stick with the more-readable three-line if-test version?
ETA: Note: We do have in the code:
option(BUILD_WITH_FLAP "Use FLAP for command line processing" ON) if (BUILD_WITH_FLAP) find_package(FLAP REQUIRED) endif ()
and I am building with