2

I have a cmake project as below

./CMakeList.txt
    ...
    option( FOO "foo var" "MyFoo")
    add_subproject( a )

./a/CMakeList.txt
    ...
    if("${FOO}" STREQUAL "MyFoo")
        message("Using Foo from Parent")
    else()
        message("Foo not passed from Parent")
    endif()

I want the FOO variable to be passed from the parent scope to the 'a' sub project; Is it possible? How to do it?

Update 1

./CMakeList.txt
    ...
    unset(FOO_VAR CACHE)
    set( FOO_VAR ${FOO} CACHE STRING "foo variable")
    add_subproject( a )

./a/CMakeList.txt
    ...
    string(COMPARE EQUAL "${FOO_VAR}" "MyFoo" result)
    if(result)
        message("Using Foo from Parent")
    else()
        message("Foo not passed from Parent")
    endif()

using this now I am getting "Using Foo from Parent"

Thanks @Tsyvarev

Hari
  • 21
  • 3
  • 1
    `option` defines TRUE/FALSE variable. For variable which can take any string value, use `set(CACHE)` construction: `set(FOO "MyFoo" CACHE STRING "FOO variable")`. Also, when compare variable with a string, read that answer: https://stackoverflow.com/a/19988856/3440745. – Tsyvarev May 03 '18 at 17:40
  • why I had to use 'if("${FOO}" STREQUAL "MyFoo")' instead of 'if(FOO STREQUAL "MyFoo")' is , sometimes the FOO may be not defined as we are passing this variable from a build script and in that case it will get evaluated to 'if( STREQUAL "MyFoo")' which is invalid – Hari May 04 '18 at 04:46
  • 1
    Construction `if(FOO STREQUAL "MyFoo")` is perfectly valid in your case: if `FOO` variable is defined, it compare its value with "MyFoo" string, if `FOO` variable is undefined, "FOO" string is compared with "MyFoo", which is FALSE. Note, that `set(CACHE)` construction is used when you expect the variable to be set in `cmake` invocation (or in CMake GUI). If you just want to set variable for the subproject, simple `set(FOO "MyFoo")` is sufficient. – Tsyvarev May 04 '18 at 08:03
  • Thanks @Tsyvarev – Hari May 10 '18 at 06:41

0 Answers0