How can a CMake variable be hidden?

2019-07-25 13:02发布

I have a CMake project which lets a globally set variable (set with -DARDUINO_SDK_PATH=/a/b/c on command line) disappear i.e. suddenly the given value is gone which leads to a fatal error.

I know there are different ways to "hide" a variable (e.g. inside functions or external projects)

In my case:

  • the variable is not being set explicitly anywhere in the code (e.g. via set() or find_path())
  • the access which leads to the error is on top level (i.e. not inside a function)
  • there are instructions (i.e. same file/line) where in one case the variable has the value it's been given and the next time it's gone

Tracing the variable with variable_watch(ARDUINO_SDK_PATH) I can see that everything works fine before the compiler is being checked:

cmake -DARDUINO_SDK_PATH=/a/b/c <path>
...
... everything fine, ${DARDUINO_SDK_PATH} == '/a/b/c' everywhere
...

-- Check for working C compiler: /usr/bin/avr-gcc

...
... here the variable is empty and not being traced any more
...

Here is my suggestion: Does the compiler check (indicated by check for working C compiler .. on the terminal) have it's own variable space and does not know variables provided on command line?

Note: This question is a generalization of this question, which has become way too specialized but might offer some useful background information.

2条回答
该账号已被封号
2楼-- · 2019-07-25 13:41

I'm not sure whether this is a bug or a feature but (at least some) CMake variables are not available in certain steps of the CMake configuration procedure.

You can check this by adding something like this to your toolchain file:

MESSAGE("FOO: ${FOO}")

and run CMake like this

cd build-dir
cmake -DFOO=TEST ..

You will likely see FOO printed with value TEST once in the beginning of the configuration process and later printed again but being empty.

Just don't access variables from the global space inside a toolchain file (doesn't belong there anyway).

查看更多
forever°为你锁心
3楼-- · 2019-07-25 13:49

That any modification to variable is not traced after the variable_watch() command seems like a bug somewhere in CMake to me.

Generally speaking a "cached CMake variable" can be hidden by a "normal CMake variable" with the same name. But e.g. find_path() won't run again or modify a variable if already set.

Here is an example:

cmake_minimum_required(VERSION 2.4)

project(VariableWatchTest NONE)

variable_watch(MY_TEST_VAR)

set(MY_TEST_VAR "something" CACHE INTERNAL "")
message("${MY_TEST_VAR}")

set(MY_TEST_VAR "hiding something")
message("${MY_TEST_VAR}")

unset(MY_TEST_VAR)
message("${MY_TEST_VAR}")

find_path(MY_TEST_VAR NAMES "CMakeLists.txt" HINTS "${CMAKE_CURRENT_LIST_DIR}")
message("${MY_TEST_VAR}")

Would give (without the variable_watch() messages:

-- something
-- hiding something
-- something
-- something

References

查看更多
登录 后发表回答