60

I have a problem using option together with if-else statement in cmake.

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?

Hakim
  • 3,225
  • 5
  • 37
  • 75
Alex
  • 3,301
  • 4
  • 29
  • 43

3 Answers3

58

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.

Simon
  • 31,675
  • 9
  • 80
  • 92
  • 7
    `rm CMakeCache.txt` or just move it to the trash/recycle bin. – Simon Mar 18 '14 at 14:16
  • 1
    If we set the actual value of an option while calling CMake that will be overwritten. There is no need to remove CMakeCache.txt. We need to remove CMakeCache.txt only if we decide not to specify the actual value and we want to use the default, while in a previous run of cmake we did specify a value different than the default one. – Perennialista Sep 07 '17 at 22:34
18

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

Daniel
  • 1,319
  • 14
  • 19
  • 2
    This doesn't work for me, I actually have to execute cmake with "-DUSE_MY_LIB=OFF" to make it work. If I simply omit it, then it keeps behaving as if were called with "ON" – m4l490n Dec 03 '18 at 20:26
  • Also @m4l490n have you tried adding a set in the if-else section? If apparently doesnt work for me. – Jason Apr 24 '19 at 22:27
2

Try this, it works for me

unset(USE_MY_LIB CACHE)
hailinzeng
  • 966
  • 9
  • 24
Karl
  • 39
  • 1