如何隐藏CMake变量?

问题描述:

我有一个CMake项目,该项目允许全局设置变量(在命令行上用 -DARDUINO_SDK_PATH =/a/b/c 设置)消失,即突然给定值不见了,导致致命错误.

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)

就我而言:

  • 未在代码中的任何地方中显式设置变量(例如,通过 set() find_path()))
  • 导致错误的访问位于顶层(即不在函数内部)
  • 有一些指令(即同一文件/行),在一种情况下,变量具有的值是给定的,而下一次它消失了
  • 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

使用 variable_watch(ARDUINO_SDK_PATH)跟踪变量我可以看到在检查编译器之前一切正常:

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
...

这是我的建议:编译器检查(在终端上由检查工作的C编译器.. 所指示)是否具有自己的变量空间,并且不知道命令行中提供的变量?

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.

我不确定这是bug还是功能,但是(至少某些)CMake变量在CMake配置过程的某些步骤中不可用.

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}")

并像这样运行CMake

and run CMake like this

cd build-dir
cmake -DFOO=TEST ..

在配置过程开始时,您可能会看到一次将 FOO 打印为值 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).