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

Viewed 867

For example, in CMakeLists.txt, I can define path:

add_definitions(-DMY_PATH="/my/path")

In C++ code, I can access the variable by

std::string my_path = MY_PATH

This works fine. Now, if I instead define a variable in CMakeLists.txt as follows:

add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})

Then, I get the following error:

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;

So, why is this different? How do I convert the cmake variable to a string in C++ code?

1 Answers

When you use this defintion:

 add_definitions(-DMY_PATH=${CMAKE_BINARY_DIR})

you will get something like this in your code:

 std::string my_path = /home/my_path

which obviously leads to a syntax error, you need to add double quotes:

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