【问题标题】:How to modify or redefine the Macro value from command line using CMake? [duplicate]如何使用 CMake 从命令行修改或重新定义宏值? [复制]
【发布时间】:2021-07-17 07:23:23
【问题描述】:

我想使用CMakeList.txt 从命令行更改宏值。我有

#ifndef NUMBER
#define NUMBER  1
#endif

#ifndef NAME
#define NAME "MyName"  //string format
#endif

我找到了一些链接 -> How to define a C++ preprocessor macro through the command line with CMake?。他们说在 CMake 中添加 add_definitions(-DNUMBER=5) 并且它正在工作我可以使用这种方式更改值。

我想要一些可以使用命令行更改值的方法。喜欢 add_definitions(-DNUMBER=NUMBERX) 从命令行我们提供号码cmake NUMBERX=100. and NAMEX="ALEXA". 或者以其他方式代替add_definitions()

【问题讨论】:

  • 如果您正确拼写 add_definitions,它可能会起作用。定义中没有 a
  • 即使你提到的问题也有the answer with option-approach,它允许有条件地设置特定的宏定义,具体取决于命令行参数。 The answer to the duplicate question描述了将命令行值直接用作宏值。

标签: c cmake


【解决方案1】:

您可以为用户添加一个缓存变量,以便在配置项目时提供此选项。对于修改现有项目,我建议使用cmake-gui;缓存变量将显示在那里供您修改。

set(MY_PROJECT_DEFINITION_NAME "default-value" CACHE STRING "compiler definition for the NAME macro") # you could choose another name for the variable, of course

#I recommend adding the definition on a per-target basis, but it could be used with add_definitions too
target_compile_definitions(my_project PRIVATE "NAME=${MY_PROJECT_DEFINITION_NAME}") # another visibility may be appropriate

使用配置您的项目

cmake -D "MY_PROJECT_DEFINITION_NAME=non-default-value" -S source_dir_path -B build_dir_path

留下-D "MY_PROJECT_DEFINITION_NAME=non-default-value" 将导致MY_PROJECT_DEFINITION_NAME 获得default-value 的值。

您可能想看看documentation of the set command btw 中的确切语法/类型选项。

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 2013-09-06
    • 2022-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 2013-10-09
    相关资源
    最近更新 更多