问题描述
例如,在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}")