【问题标题】:How do I convert a cmake variable to a string in C++ code?如何在 C++ 代码中将 cmake 变量转换为字符串?
【发布时间】:2021-01-03 21:28:35
【问题描述】:

例如,在 CMakeLists.txt 中,我可以定义路径:

add_definitions(-DMY_PATH="/my/path")

在 C++ 代码中,我可以通过

std::string my_path = MY_PATH

这很好用。现在,如果我改为在 CMakeLists.txt 中定义一个变量,如下所示:

add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})

然后,我收到以下错误:

error: expected primary-expression before ‘/’ token
/home/user/development/include/helper.hpp:33:32: note: in expansion of macro ‘MY_PATH’
       const std::string path = MY_PATH;
                                ^~~~~~~
<command-line>:0:10: error: ‘home’ was not declared in this scope
/home/user/development/include/helper.hpp:33:32: note: in expansion of macro ‘MY_PATH’
       const std::string path = MY_PATH;

那么,为什么会有所不同?如何将 cmake 变量转换为 C++ 代码中的字符串?

【问题讨论】:

    标签: c++ makefile cmake cmakelists-options


    【解决方案1】:

    当你使用这个定义时:

     add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})
    

    你会在你的代码中得到类似的东西:

     std::string my_path = /home/my_path
    

    显然会导致语法错误,需要加双引号:

     add_definitions(-DMY_PATH="${CMAKE_BINARY_DIR}")
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2021-10-27
      • 1970-01-01
      • 2011-03-09
      相关资源
      最近更新 更多