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

问题描述

例如,在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}")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...