cmake if else with option

左心房为你撑大大i 提交于 2019-12-03 14:33:51

问题


I am with problem to use option together if-else in the cmake.

project(test)

option(TESTE "isso é um teste" OFF)

if(TESTE)
  message("true")
else()
  message("false")
endif()

add_executable(test main.cpp)

It always display true even if I put OFF at the option, what am I doing wrong?


回答1:


That's because the value of the option is stored in the cache (CMakeCache.txt).

If you change the default value in the CMakeLists but the actual value is already stored in the cache, it will just load the value from the cache.

So to test the logic in your CMakeLists, delete the cache each time before re-running CMake.




回答2:


I had a similar problem and was able to solve it using a slightly different approach.

I needed some compilation flags to be added in case cmake was invoked with an option from the command line (i.e cmake -DUSE_MY_LIB=ON). If the option was missing in the cmake invocation I wanted to go back to default case which was turning the option off.

I ran into the same issues, where the value for this option was being cached between invocations:

cmake -DUSE_MY_LIB=ON .. #invokes cmake and puts USE_MY_LIB=ON in CMake's cache.
cmake ..                 #invokes cmake with the cached option ON, instead of OFF

The solution I found was clearing the option from within CMakeLists.txt after the option was used:

option(USE_MY_LIB "Use MY_LIB instead of THEIR_LIB" OFF) #OFF by default
if(USE_MY_LIB)
    #add some compilation flags
else()
    #add some other compilation flags
endif(USE_MY_LIB)
unset(USE_MY_LIB CACHE) # <---- this is the important!!

Note: The unset option is available since cmake v3.0.2



来源:https://stackoverflow.com/questions/22481647/cmake-if-else-with-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!