3

例如,在 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++ 代码中的字符串?

4

1 回答 1

4

当您使用此定义时:

 add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})

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

 std::string my_path = /home/my_path

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

 add_definitions(-DMY_PATH="${CMAKE_BINARY_DIR}")
于 2020-09-17T02:35:17.563 回答