Variables set with PARENT_SCOPE are empty in the corresponding child scope. Why?

后端 未结 4 2114
轮回少年
轮回少年 2021-02-12 16:17

Consider the following minimal example:

.
├── bar
│   └── CMakeLists.txt
└── CMakeLists.txt

where ./CMakeLists.txt is



        
4条回答
  •  灰色年华
    2021-02-12 17:03

    Each variable in the cmake has it's own scope so it is dangerous use case where a variable automatically propagates in a child context, because it can interfere with it from a parent scope!

    But you can set just another variable in a child scope to test it later instead of rereading a parent one:

    ./bar/CMakeLists.txt:

    set( BAR "Exists in parent scope only." PARENT_SCOPE )
    set( _somerandomid_BAR "Exists in child scope only.")
    message( STATUS "Variable BAR in ./bar/ = ${_somerandomid_BAR}" )
    

    Now, if you have loops in your code, then you can test both variables:

    foreach(...)
      ...
      # read a variable token name and token value, for example, from a configuration file
      set(my_var_name_token ...)
      set(my_var_value_token ...)
      ...
      # parse a variable name and value tokens into a real name and value
      set(my_var_name ...)
      set(my_var_value ...)
      ...
      if (DEFINED ${my_var_name})
        if (DEFINED local_${my_var_name})
          message("has been defined before and was resetted");
        else()
          message("has been defined before and was not resetted");
        endif()
      else()
        if (DEFINED local_${my_var_name})
          message("has not been defined before and was setted");
        else()
          message("has not been defined before and was not touched");
        endif()
      endif()
      ...
      # sets parsed name and value into cmake context
      set(${my_var_name} "..." PARENT_SCOPE)
    
      # Do save all values has been setting from this function to differently compare and 
      # validate them versus already existed before:
      # 1. If has been set before, then must be set to the same value, otherwise - error
      # 2. If has not been set before, then should set only once, otherwise - ignore new 
      # value (a constant variable behaviour)
      set(local_${my_var_name} "...")
      ...
    endforeach()
    

提交回复
热议问题