How to use condition in cmake generator expression

I would like to compile a library as shared or static based on other variable eg:

add_library(MyLibrary $<$<IF:${BUILD_SHARED_LIBS},SHARED,STATIC> ${SOURCES})

For clarity I expect this to be equivalent with the following:

if(BUILD_SHARED_LIBS)
  add_library(MyLibrary SHARED ${SOURCES})
elseif()
  add_library(MyLibrary STATIC ${SOURCES})
endif()

Upvotes: 3

Views: 1474

Answers (1)

compor
compor

Reputation: 2339

AFAIK, you cannot do that with generator expressions (no way to query that aspect according to doc), since BUILD_SHARED_LIBS is there for exactly that reason; to allow you to select its value during configuration (using the -D command line option). This will work only if you do not set the library type explicitly as in your code, but like this

add_library(MyLibrary ${SOURCES})

Actually, that is the recommended practice. If you need to influence its value in association with some other condition, you can override it with the usual if()/else() logic, making sure that you print at least an informative message() for the user.

However, an even better approach would be to push those decisions to the user (via options) and check for the illegal combinations, issuing a message(FATAL_ERROR). Even if that condition is determined automatically, this is still a tactic that has merit.

Upvotes: 2

Related Questions