Stewart
Stewart

Reputation: 5002

CMAKE default value for options doesn't work

If I have the following line. Then I would expect TEST_OPTION to be set to ON by default.

option( TEST_OPTION "A test option" ON)

When I test it, it doesn't seem to be ON by default. To test, I am compiling a simple application:

int main() {

  #ifdef TEST_OPTION
    #error "TEST_OPTION encountered"
  #endif 
  return 0;
}

I also have a simple CMakeLists.txt:

cmake_minimum_required(VERSION 2.6)
project(test)

add_executable(test main.cpp)

option( TEST_OPTION "A test option" ON)

if(TEST_OPTION)
  target_compile_definitions(test PRIVATE TEST_OPTION)
endif(TEST_OPTION)

If I try to compile with $ cmake && cmake --build ., I would expect to encounter the compile error, but I don't! If I replace option( TEST_OPTION ... ) with set(TEST_OPTION ON), then I get the compile error that I expected.

Can someone explain why option() doesn't set the option to the default value by default?

Upvotes: 6

Views: 3672

Answers (2)

Martyn Russell
Martyn Russell

Reputation: 21

For your case, you can use cmake -UTEST_OPTION. This argument allows for globbing too. In my case, I fixed this by updating cached arguments with the cmake -UCONFIG_BUILD_* ... where CONFIG_BUILD_TESTS defaults to ON.

Upvotes: 2

Stewart
Stewart

Reputation: 5002

Solution: The cmake cache doesn't seem to refresh when you change an option's default. Therefor, by first constructing it with "OFF" selected, the "ON" option was completely ignored. To solve this I just had to delete the generated cmake artifacts and run cmake again.

Upvotes: 9

Related Questions