如何将 cmake 变量转换为 C++ 代码中的字符串?

How do I convert a cmake variable to a string in C++ code?

比如在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;

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

当您使用此定义时:

 add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})

你会在你的代码中得到这样的东西:

 std::string my_path = /home/my_path

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

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