通过命令提示符将参数传递给CMAKE

bweufnob  于 2022-11-11  发布在  其他
关注(0)|答案(2)|浏览(218)

我为我的项目准备了一个makefile,我可以用它来传递一个控制某些编译标志的参数。现在我想用CMake来做同样的事情。我已经创建了CMakeLists.txt,但是我不知道如何传递参数并检查CMakeLists.txt中的参数值。
我的Makefile示例:

ifeq "$(MY_VARIABLE)" "option_value"
      //setting some flags
else
      //setting some other flag
endif

然后我使用make MY_VARIABLE=option_value调用make。在CMake中,从命令提示符获取参数并基于此设置标志的方法是什么?

c3frrgcw

c3frrgcw1#

在CMakeLists.txt文件中,创建一个缓存变量,如下所示:

SET(MY_VARIABLE "option_value" CACHE STRING "Some user-specified option")

来源:https://cmake.org/cmake/help/latest/command/set.html#set-cache-entry
然后,使用GUI(ccmake或cmake-gui)设置该高速缓存变量,或在cmake命令行上使用-D指定变量得值:

cmake -DMY_VARIABLE:STRING=option_value2

如果您的选项实际上是布尔值,请将缓存变量修改为布尔值。

ds97pgxw

ds97pgxw2#

在Ubuntu 16.04上运行CMake 3.13

此方法更灵活,因为它不将MY_VARIABLE约束为类型:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

相关问题