Ral*_*lff 5 c++ makefile cmake cmakelists-options
例如,在 CMakeLists.txt 中,我可以定义路径:
\nadd_definitions(-DMY_PATH="/my/path")\nRun Code Online (Sandbox Code Playgroud)\n在 C++ 代码中,我可以通过以下方式访问变量
\nstd::string my_path = MY_PATH\nRun Code Online (Sandbox Code Playgroud)\n这很好用。现在,如果我在 CMakeLists.txt 中定义一个变量,如下所示:
\nadd_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})\nRun Code Online (Sandbox Code Playgroud)\n然后,我收到以下错误:
\nerror: expected primary-expression before \xe2\x80\x98/\xe2\x80\x99 token\n/home/user/development/include/helper.hpp:33:32: note: in expansion of macro \xe2\x80\x98MY_PATH\xe2\x80\x99\n const std::string path = MY_PATH;\n ^~~~~~~\n<command-line>:0:10: error: \xe2\x80\x98home\xe2\x80\x99 was not declared in this scope\n/home/user/development/include/helper.hpp:33:32: note: in expansion of macro \xe2\x80\x98MY_PATH\xe2\x80\x99\n const std::string path = MY_PATH;\nRun Code Online (Sandbox Code Playgroud)\n那么,为什么会有所不同呢?如何将 cmake 变量转换为 C++ 代码中的字符串?
\n当您使用此定义时:
add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})
Run Code Online (Sandbox Code Playgroud)
你会在你的代码中得到类似这样的东西:
std::string my_path = /home/my_path
Run Code Online (Sandbox Code Playgroud)
这显然会导致语法错误,您需要添加双引号:
add_definitions(-DMY_PATH="${CMAKE_BINARY_DIR}")
Run Code Online (Sandbox Code Playgroud)