質問

Is it possible in CMake to have inline conditonals within argument lists somehow?

Example of what I want (the whole IF line is not parsed but handled like a string, but I want it parsed):

LIST(APPEND myList
  foo
  bar
  IF(MINGW) hello ENDIF()
  cool
)

instead of what I have now

LIST(APPEND myList
  foo
  bar
)

IF(MINGW)
  LIST(APPEND myList hello)
ENDIF(MINGW)

LIST(APPEND myList cool)

Something similar to the example would make my CMakeLists.txt files way easier to read at many places! Especially if there's a specific order that needs be kept the CMake code gets very big without inline conditionals sometimes, because one needs to repeat the same call everytime.

Note: I took LIST as an example here, the question should be seen as general for other functions, too!

役に立ちましたか?

解決

There is currently no such feature in CMake, although I agree it would be quite useful in certain situations.

I usually rely on the fact that CMake has no problem with ignoring empty values in most contexts:

if(MINGW)
    set(ADDITIONAL_ITEMS hello)
endif()

list(APPEND mylist
  foo
  bar
  ${ADDITIONAL_ITEMS}
  cool
)

It's not perfect, but IMHO at least cleaner than appending to the same list twice. The same technique also works for conditionally passing function parameters.

Note that depending on the context where this is needed, CMake generator expressions might be an option:

target_link_libraries(t foo bar $<$<BOOL:${SOME_CONDITION}>:hello> cool)

他のヒント

You can use the PLATFORM_ID generator expression, depending on what you're doing with the list you're creating:

http://www.cmake.org/cmake/help/v3.0/manual/cmake-generator-expressions.7.html

target_link_libraries(t foo bar $<$<PLATFORM_ID:MINGW>:hello> cool)

Apart from target_link_libraries, such expressions work with target_include_directories, target_compile_definitions, target_compile_options, target_compile_features (CMake 3.1), target_sources (CMake 3.1), file(GENERATE), install(FILES), add_custom_target etc. You get the idea :).

Unfortunately, no.

The only way to conditionally build lists without repetition is with list APPEND (BTW unless ordering matters, you can simplify it by adding cool in the list definition).

CMake syntax is quite verbose and limited and it is often hard not to repeat yourself. That is why I have sometimes ended up generating parts of the CMake code in another language.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top