简体   繁体   English

cmake if else with option

[英]cmake if else with option

I have a problem using option together with if-else statement in cmake.我在 cmake 中将optionif-else语句一起使用时遇到问题。

project(test)

option(TESTE "isso é um teste" OFF)

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

add_executable(test main.cpp)

It always displays true even if I put OFF in the options, what am I doing wrong?即使我在选项中关闭它,它也总是显示为true ,我做错了什么?

That's because the value of the option is stored in the cache ( CMakeCache.txt ).这是因为选项的值存储在缓存中 ( 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.如果您更改了 CMakeLists 中的默认值,但实际值已经存储在缓存中,它只会从缓存中加载该值。

So to test the logic in your CMakeLists, delete the cache each time before re-running CMake.因此,要测试 CMakeLists 中的逻辑,请在每次重新运行 CMake 之前删除缓存。

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 (ie cmake -DUSE_MY_LIB=ON ).我需要的情况下的cmake要添加一些编译标志与来自命令行的选项(即,被调用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.如果在cmake调用中缺少该选项,我想回到关闭该选项的默认情况。

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:我找到的解决方案是在使用该选项后CMakeLists.txt 中清除该选项:

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注意: unset选项自 cmake v3.0.2 起可用

试试这个,它对我有用

unset(USE_MY_LIB CACHE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM